Apr 22, 2024 iOS

SwiftUI @State var initialization issue

In SwiftUI, initializing a @State variable directly within the init() method of a View can lead to unexpected behavior. Let’s explore the issue and find a solution.

The problem arises because SwiftUI doesn’t allow you to change the value of a @State variable in the initializer. However, you can initialize it. Here’s how you can work around this:

  1. Remove the Default Value: Instead of providing a default value for your @State variable, leave it uninitialized. For example:
@State var fullText: String // No default value of ""

2. Initialize Using Underscore Syntax: Use the underscore syntax to set the @State directly, bypassing the property wrapper accessor. In your init(), initialize the @State like this:

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

By following these steps, you can initialize your @State variable without encountering the “Accessing State<String> outside View.body” error. Remember that @State should ideally be initialized inline or through other appropriate mechanisms, such as @Binding or @ObservedObject1.

Keep in mind that SwiftUI encourages using @Binding to provide access to state that isn’t local to your view. If possible, consider using bindings for more robust and predictable behavior2.