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.

  1. What do @State, @Binding and @Bindable do, and who owns the data? 8.3.1 · L1
    @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…
  2. How does the SwiftUI environment work, and when should you use it instead of passing a parameter? 8.3.2 · L2
    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>.

  1. How does the Observation framework differ from ObservableObject, and how does tracking work? 8.3.3 · L3
    With ObservableObject you mark properties @Published, and the object publishes objectWillChange for every change; any view that holds the object…

More in SwiftUI