Fix: Fatal Error Accessing State Outside View Body in SwiftUI

Written by

in

Quick answer: SwiftUI prohibits writing to @State properties in a view’s initializer because the property wrapper’s storage isn’t ready yet. Fix it by either initializing the underlying State storage directly with _property = State(initialValue: value) or by deferring the assignment to the view’s onAppear modifier.

Why this happens

SwiftUI’s @State property wrapper manages persistent storage for value types across view updates. When you declare @State var fullText: String = "", SwiftUI creates a hidden storage location that survives view re-creation. However, this storage is only allocated after the view’s initializer finishes and before body is first evaluated.

Writing to self.fullText = ... inside init() attempts to use the property wrapper’s setter before its storage exists. The runtime detects this and traps with:

Thread 1: Fatal error: Accessing State outside View.body

The error message is literal: you are accessing the @State backing store outside the view’s body lifecycle, where SwiftUI guarantees it is valid.

How to fix it

1. Initialize the underlying State storage directly (recommended)

Use the synthesized underscore-prefixed property (_fullText) to assign a new State instance with the desired initial value. This bypasses the wrapper’s setter and writes straight to the storage slot SwiftUI has reserved.

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

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

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

Why this works: _fullText is the actual State<String> struct that holds the value. Constructing it with State(initialValue:) is exactly what the property wrapper does when you write @State var fullText = "default" at the declaration site. Doing it manually in init is safe because the storage slot is already allocated by the time your initializer runs.

Note: The underscore property is an implementation detail, but it has been stable since SwiftUI’s introduction and is the pattern Apple’s own frameworks use for programmatic @State initialization.

2. Defer assignment to onAppear

If you prefer not to touch the underscore property, move the assignment into the view’s onAppear callback. At that point the view is in the view hierarchy and @State is fully active.

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

    var body: some View {
        TextField("Label", text: $fullText)
            .onAppear {
                fullText = list[letter] ?? ""
            }
    }
}

Trade-off: The text field will briefly show the empty default value before onAppear fires. For most forms this is unnoticeable, but if the flash is unacceptable, use fix #1.

3. Lift state to an ObservableObject (for complex logic)

When initialization involves non-trivial logic—network calls, decoding, multiple dependencies—move the data into a separate model object.

final class LetterModel: ObservableObject {
    @Published var fullText: String
    init(letter: String) {
        let list = ["a": "Letter A", "b": "Letter B"]
        fullText = list[letter] ?? ""
    }
}

struct StateFromOutside: View {
    @StateObject var model: LetterModel

    init(letter: String) {
        _model = StateObject(wrappedValue: LetterModel(letter: letter))
    }

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

This keeps the view lightweight and makes the initialization logic testable.

How to prevent it

  • Never write to @State, @Binding, @StateObject, or @ObservedObject properties inside a view’s init.
  • Declare @State without a default value when you plan to initialize it in init via the underscore property.
  • Prefer StateObject/ObservedObject for any initialization that does more than pick a simple default.
  • Use onAppear only for side-effects (analytics, starting timers) or when a one-frame default flash is acceptable.

FAQ

Can I use self._fullText = State(wrappedValue: ...) instead?

No. State does not have a wrappedValue initializer; the correct label is initialValue. The property wrapper’s projected value ($fullText) is a Binding, not the storage itself.

Does this apply to @Binding as well?

Yes. @Binding also has an underscore storage property (_bindingName) that you can initialize in init with Binding(get: ..., set: ...) if you need to construct a binding programmatically. However, bindings are usually passed from a parent view, so manual initialization is rare.

Will the underscore property ever be removed or renamed?

It has been stable since iOS 13 / macOS 10.15. Apple uses the same pattern in their own code (e.g., StateObject‘s _stateObject). While technically private, it is the supported way to programmatically initialize property-wrapped state in a view initializer.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.