SwiftPumpkin

22 of 22 · SwiftUI architecture

State Management

SwiftUI state management is about ownership: every piece of state has exactly one owner, and every other view borrows it. The property wrapper you choose declares who owns what.

How it's wired

$valueWrites backOwns, passes downParent view@State ownsChild view@Binding borrowsModel@Observable, shared
calls or tellsreports backEvery piece of state has exactly one owner. Everyone else borrows it.
  • @State is owned by this view.
  • @Binding borrows from a parent.
  • @Environment is handed down.
  • An @Observable model holds shared app data.
PartOwnsLooks like
@StateView-owned value or model lifetime@State private var draft
@BindingRead-write borrow from a parent@Binding var selection
@EnvironmentHanded down the tree@Environment(AppContainer.self)
@ObservableShared model, per-property tracking@MainActor @Observable class

Mistakes that ship

  • Initializing @State from a parameter uses only the first value. Later changes from the parent are ignored.
  • Duplicated sources of truth drift. Derive values instead of copying them into new state.
  • @Observable tracks reads per property; ObservableObject invalidates the whole object on any change. Mark observable models @MainActor.
  • A missing @Environment object crashes at runtime, not compile time. Inject at the root and in previews.

How I choose

Local UI state@State, private.
A child edits a parent's value@Binding.
Shared app data@Observable model, owned once, passed down.
Dependencies for a subtree@Environment.

Compared

Who owns the state

@State@Binding@Environment@Observable
OwnerThe viewParentAncestorWhoever holds it
WritesThe viewChild, through parentVia the objectModel methods
LifetimeView identityParent'sAncestor'sOwner's @State

Expert notes

  • Ask "who owns this?" before picking a wrapper. One owner, everyone else borrows.

Check yourself

Answer out loud before you reveal. Recall is what makes it stick.

30-second answer

Explain State Management in 30 seconds.

SwiftAsked directly

With an @Observable model, how do you choose between @State, @Environment, @Bindable, or a plain property?

iOS codingAsked indirectly

A child Play button must toggle the parent's isPlaying, but passing a copy loses sync. What's the correct wiring?

SwiftAsked indirectly

After migrating to @Observable, a screen's model resets whenever its parent redraws. What's wrong?

System designAsked indirectly

Two architecture proposals both handle model data fine. How do you compare them fairly?

Read it in the app's source