SwiftUI & state

View composition, @State/@Binding/@Observable, environment, and the render cycle. Choosing the right property wrapper is the iOS equivalent of Compose recomposition.

About 21 min read3-question knowledge check

The mental model

SwiftUI is a spreadsheet for your UI, the same way Jetpack Compose is — you write a formula (body) that describes what the screen looks like *given some state*, and the framework recomputes it whenever that state changes. You never reach into a view and mutate it (label.text = ...); you change state, and SwiftUI re-derives the view. The declarative promise is that the UI cannot drift out of sync with the data, because the UI is a function of the data.

The part that trips people up — and the part interviews probe relentlessly — is choosing the right property wrapper for each piece of state, because the wrapper decides three things at once: who owns the state, whether changing it invalidates the view, and how long it lives. Pick wrong and you get one of two classic bugs: state that resets every time the view re-renders (because you didn't give it an owner), or a view that doesn't update when the data changes (because you didn't subscribe it). This is the exact iOS analogue of "what triggers recomposition?" in Compose — here it is "which wrapper owns and observes this state?"

The mental map for the modern wrappers (iOS 17+, the Observation framework):

  • **@State** — this view owns a piece of state. For value types (a Bool, a String) it is the source of truth; for a reference type marked @Observable, @State owns the instance and keeps it alive across re-renders.
  • **@Binding** — a two-way reference to state owned by *someone else*, so a child can read and write a parent's @State without owning it.
  • **@Observable* (a macro on a class) — a reference-type model whose properties SwiftUI observes; when a property a view reads* changes, only that view re-renders.
  • **@Environment** — dependency injection down the view tree, for shared things (a theme, a model, the scene phase) without threading them through every initializer.

The idea that separates a passing answer from a strong one: **a SwiftUI view is a cheap, ephemeral struct that is created and thrown away constantly; the state must live somewhere that outlives it.** @State and @Observable provide that durable home behind the disposable view, which is why picking the wrapper correctly is the whole skill.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision