DevPrep

All topics › SwiftUI

How does Observation track changes, and where does fine-grained tracking break down?

Senior PRO

The gist

The @Observable macro turns every stored property into a computed one: the getter calls access(keyPath:) on an ObservationRegistrar, the setter wraps the write in withMutation(keyPath:). SwiftUI evaluates body inside a mechanism equivalent to withObservationTracking: every access that happens synchronously during body is recorded as a dependency of that node. The first change to any of them invalidates the node, and on the next body the dependency set is collected from scratch.

Hence the rule: a dependency is an "instance + property" pair read in body. Not the model's type, and not the mere fact that the model was passed to the view.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store