In SwiftUI, why does a view use @State for a value it changes, instead of a plain var stored property on the view struct?
answer
- views are short-lived values
- body cannot mutate self
- storage SwiftUI manages for you
- nonmutating setter on wrappedValue
- a write updates the views that read it
basics
~20 sA SwiftUI view is a short-lived struct whose body cannot mutate it. @State keeps the value in storage SwiftUI manages outside the struct, so writes survive the struct being recreated and update the views that read the value.
solid answer
~50 sA `View` is a value type that SwiftUI creates and discards freely, and `body` is a non-mutating getter, so a `Button` action that assigns to a plain `var` does not compile; even a value set from outside would be lost the next time the parent rebuilt the struct. `@State` tells SwiftUI to manage the storage: the value lives outside the struct for as long as the view keeps its identity, writes go through a setter that does not mutate the struct, and when the value changes SwiftUI updates the parts of the hierarchy that depend on it. Declare it `private`, give it an initial value at the declaration, and place it in the highest view that needs it; children receive it read-only as a plain property or read-write as a `Binding`. It suits transient UI state, such as whether a focus timer is running, not data that must survive a relaunch.
code
swift · 16 linesimport SwiftUI
struct FocusTimerView: View {
@State private var isRunning = false
var body: some View {
VStack(spacing: 16) {
Text(isRunning ? "Focusing" : "Ready")
.font(.title)
Button(isRunning ? "Pause" : "Start") {
isRunning.toggle()
}
.buttonStyle(.borderedProminent)
}
}
}go deeper
Recall that a view is a struct SwiftUI recreates and that body cannot mutate it; @State moves the value into storage SwiftUI keeps, and a write redraws whatever reads it.
Explain the mechanics: the wrapper's nonmutating setter, storage kept per view identity, DynamicProperty values supplied before body runs, and why the property is private with its value at the declaration.
Show placement judgment: state in the least common ancestor, one source of truth shared down as a value or a binding, and spotting non-private state set from an initializer in review.
Frame @State as the cheapest ownership tool: argue where transient UI state ends and model data begins, so a codebase does not push shared or persisted data into view-local storage.
## Why a plain property is not enough In SwiftUI a **view** is a `struct` that conforms to the `View` protocol. It is a lightweight description of a piece of interface, not a long-lived object on screen. SwiftUI creates these structs whenever a parent's `body` runs, uses what they describe to update the screen, and throws the structs away. Two consequences follow for a value the view itself wants to change: - **`body` cannot mutate the struct.** The `body` requirement is a getter, and the closures inside it, such as a `Button` action, capture `self` as immutable. Assigning to a plain `var` stored property there is rejected by the compiler. - **The struct does not last.** Even if you found a way to change a stored property, the next time the parent re-ran its `body` it would build a fresh struct with the property's original value, and the change would be gone. - **Nothing would redraw.** A plain property is invisible to SwiftUI's dependency tracking, so changing it would not tell SwiftUI that anything on screen is out of date. ## What `@State` changes `@State` marks a property as a **source of truth managed by SwiftUI**. The property you declare is a thin handle; the value itself lives in storage that SwiftUI keeps on the view's behalf for as long as the view keeps its **identity** (its position and explicit id in the hierarchy). In practice that gives you three things: 1. **Writes are allowed from `body`.** In the `State` property wrapper, `wrappedValue` is declared `get` / `nonmutating set`, so writing goes to SwiftUI's storage rather than mutating the struct. Under Xcode 27 `@State` expands as the `State()` macro instead, and the documentation keeps the same reading and writing model. 2. **Values survive struct re-creation.** When the parent rebuilds the struct, SwiftUI hands the existing stored value back to the new instance before it recomputes `body`. 3. **Changes drive updates.** When the value changes, SwiftUI updates the parts of the view hierarchy that depend on it. SwiftUI finds these properties because `State`, `Binding`, `Environment` and other SwiftUI wrappers conform to the `DynamicProperty` protocol. Apple's documentation describes it simply: the view gives values to these properties before recomputing its `body`. ## Rules from Apple's documentation Apple's `State` documentation sets a short list of conventions: - **Declare it `private`.** A non-private `@State` appears in the memberwise initializer, and setting it from outside conflicts with the storage management SwiftUI provides. - **Give the initial value at the declaration**, as in `@State private var isRunning = false`. - **Put it in the highest view that needs it**, the least common ancestor of its readers, and share it downward: as a plain property for read-only access, or as a `Binding` for read-write access. - **Keep it local.** Use state only for storage that is local to a view and its subviews, and only for transient UI state such as a highlight, a filter setting or the selected row. Its life cycle mirrors the view's, so it is not persistent storage. The documentation also says you can safely mutate state properties from any thread. ## How `@State` compares with other places a view keeps data | Declaration | Who owns the value | Can the view write it? | Survives the parent rebuilding the struct? | |---|---|---|---| | `let title: String` | The parent | No | It is re-supplied by the parent each time | | `var count = 0` (plain) | The struct copy | Not from `body` | No, reset to `0` | | `@State private var count = 0` | SwiftUI, on the view's behalf | Yes | Yes, while identity is unchanged | | `@Binding var count: Int` | Some other source of truth | Yes, writes go to the owner | Yes, it points at the owner | Reference-type models (an `@Observable` class held in `@State`, or the older `ObservableObject` wrappers) and values that must persist across launches are covered in their own lessons. ## Worked example: a focus timer's start button A focus-timer screen needs to know whether the countdown is running. That flag is pure UI state: no other screen cares, and it should not survive a relaunch. So the screen owns it with `@State private var isRunning = false`, the start button toggles it, and the label and the button title read it. When the user taps, the write lands in SwiftUI's storage, SwiftUI notices that `body` read `isRunning`, and the label and button update. If the parent screen redraws for an unrelated reason, the timer view's struct is rebuilt but `isRunning` keeps its value, because the storage belongs to the view's identity, not to the struct. Two mistakes to avoid follow from the same model: duplicating the flag in a child view (two sources of truth that drift apart) and making it non-private so a parent can "set" it, which SwiftUI's storage management does not honour after the first time it creates the value.
- Why does Apple's documentation tell you to mark @State properties private?A non-private `@State` shows up in the view's memberwise initializer, and setting it from outside conflicts with the storage SwiftUI manages: SwiftUI keeps the value it already stores for that view, so a value passed in on a later initialization is not applied. Keeping it `private` makes the view the clear owner and forces outside input to arrive as a plain property or a `Binding`.
- How does SwiftUI find a @State property among a view's stored properties?`State` conforms to `DynamicProperty`, as do `Binding`, `Environment` and other SwiftUI wrappers. SwiftUI gives dynamic properties their current values before it recomputes `body`, so a read inside `body` sees the stored value rather than the declaration's initial value. A custom wrapper that conforms to `DynamicProperty` can implement `update()` to refresh itself at that same point.
- Should @State hold data the app must keep after a relaunch?No. Apple's guidance is that the life cycle of state mirrors the view's, so it suits transient UI state such as a highlight, a filter or a selected row. Small settings that must survive a relaunch belong in user defaults, and app data in a database; both are covered in their own lessons.
A @State property is like a coat-check ticket: the view struct carries only the ticket, the coat itself stays with the cloakroom (SwiftUI), and anyone holding a new copy of the ticket gets the same coat back.
- A plain var on the view struct works if you assign it inside body.
- @State turns the view struct into a long-lived object that SwiftUI keeps.
- Make @State public so a parent view can set it through the initializer.
- @State is a good place for data that must survive an app relaunch.
- Each subview should declare its own @State copy of a shared value.