UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How can I store @State value in a String array? When I attempt this, arr[0] = loanAmount from a TextField, I get the following error. “Cannot assign through subscript: ‘self’ is immutable”. What am I missing?

Forums > SwiftUI

I am new to Swift, and tried to solve this problem far too long. I have the following declared:

@State private var loanAmount = "0"    
private var arr = [String](repeating: "", count: 10)

I also tried the array with a property wrapper like this
@State private var arr = [String](repeating: "", count: 10) and 
that also didn't work'

The body of my View where I am getting the errors shown in the
code between ***.  Can anyone help?

    var body: some View {
    NavigationView {
        Form {
            HStack { //*** Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols *** 
                Text("Company Name:")
                TextField("", text: self.$companyName)
            }
            HStack {
                Text("Loan Amount:")
                TextField("", text: self.$loanAmount)
                arr[0] = loanAmount //*** Cannot assign through subscript: 'self' is immutable ***
                }
            }

3      

Is your array arr also declared with @State? If not, then as the error says, you cannot change its value as the Struct is immutable.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.