1.6 · Properties, observers, wrappers

Stored vs computed is about memory. Observers are about reacting. Wrappers are about owning the get/set. Mixing them up produces the “my didSet never fires” bugs.

Mental model. @State, @Published, @AppStorage are property wrappers. @Observable is a macro. That one distinction answers a surprising number of interview questions.

Kinds of properties

Storage, computation, laziness and observation.

  1. Stored vs computed vs lazy vs property observers (willSet/didSet)? 1.6.1 · L1
    Stored occupies memory. Computed has get/set and no storage of its own. lazy var is initialized once on first access, must be a var, and is not thread-safe by…
  2. Property observers vs overriding a setter — which do you use? 1.6.2 · L2
    Observers react to changes on that type's storage without taking over the write. Use them for logging, invalidation, or keeping a derived value in sync.…

Property wrappers

Reusable get/set logic with a $ side door.

  1. What is a property wrapper? Can you write a custom one? 1.6.3 · L2
    A type with wrappedValue (and optionally projectedValue, exposed as $foo, plus init(wrappedValue:)). Writing @Clamped var x makes the compiler store a wrapper…
  2. What is projectedValue? Give a real example. 1.6.4 · L3
    projectedValue is the value exposed through the $ prefix. The wrapper decides what it is: @Published → $name is a Publisher. @State / @Binding → $name is a…

Thread safety

What is and is not safe to touch concurrently.

  1. Are property wrappers thread-safe? Is lazy? 1.6.5 · L5
    No by default. A wrapper is exactly as safe as its implementation. lazy uses a hidden initialization flag that is not atomic — two threads can both observe…

More in Swift language