8.3 · State, Binding, Environment and Observation
Every SwiftUI screen is a function of state. The property wrappers differ in who owns the value and what reading it subscribes you to.
Mental model. Ask two questions of every piece of data: who owns it (one place only), and who needs to change it (give them a binding). Everything else just reads.
Owning and sharing state
<code>@State</code>, <code>@Binding</code>, <code>@Bindable</code> and the environment.
- What do @State, @Binding and @Bindable do, and who owns the data?
@State gives a view private, persistent storage. A view struct is recreated constantly, so SwiftUI keeps the actual value outside the struct, attached to the… - How does the SwiftUI environment work, and when should you use it instead of passing a parameter?
The environment is a set of values that flows down the view tree: system values (colorScheme, dynamicTypeSize, layoutDirection, dismiss, openURL) plus your…
Models
Observation versus <code>ObservableObject</code>.
- How does the Observation framework differ from ObservableObject, and how does tracking work?
With ObservableObject you mark properties @Published, and the object publishes objectWillChange for every change; any view that holds the object…
More in SwiftUI
- 8.1 · What a View is, and how SwiftUI knows which view is which
- 8.2 · The update loop, dependency tracking and the cost of body
- 8.4 · onAppear, task, onChange and scenes
- 8.5 · The layout negotiation, stacks, GeometryReader, safe area and custom Layout
- 8.6 · Lists, ForEach and NavigationStack
- 8.7 · Animations, PhaseAnimator, Canvas and TimelineView
- 8.8 · Preference keys and coordinate spaces
- 8.9 · Previews and the macros behind SwiftUI
- 8.10 · State, bindings, Observation and environment, checked by running them
- 8.11 · The order of events in a render, and what Swift 6 isolation means for views
- 8.12 · Sharing space, alignment guides, adaptive containers and grids, measured
- 8.13 · What a ViewBuilder produces, and saving and restoring a navigation path