SwiftUI @State var initialization issue

I would like to initialise the value of a @State var in SwiftUI through the init() method of a Struct, so it can take the proper text from a prepared dictionary for manipulation purposes in a TextField. The source code looks like this:

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

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

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

Unfortunately the execution fails with the error Thread 1: Fatal error: Accessing State<String> outside View.body

How can I resolve the situation? Thank you very much in advance!


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]!)
}

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.