SwiftUI @State var initialization issue

I would try to initialise it in onAppear.

struct StateFromOutside: View {
    let list = [
        "a": "Letter A",
        "b": "Letter B",
        // ...
    ]
    @State var fullText: String = ""

    var body: some View {
        TextField($fullText)
             .onAppear {
                 self.fullText = list[letter]!
             }
    }
}

Or, even better, use a model object (a BindableObject linked to your view) and do all the initialisation and business logic there. Your view will update to reflect the changes automatically.


Update: BindableObject is now called ObservableObject.


SwiftUI doesn't allow you to change @State in the initializer but you can initialize it.

Remove the default value and use _fullText to set @State directly instead of going through the property wrapper accessor.

@State var fullText: String // No default value of ""

init(letter: String) {
    _fullText = State(initialValue: list[letter]!)
}

It's not an issue nowadays to set a default value of the @State variables inside the init method. But you MUST just get rid of the default value which you gave to the state and it will work as desired:

,,,
    @State var fullText: String // <- No default value here

    init(letter: String) {
        self.fullText = list[letter]!
    }

    var body: some View {
        TextField("", text: $fullText)
    }
}

Tags:

Swiftui