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.
- Stored vs computed vs
lazyvs property observers (willSet/didSet)?
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… - Property observers vs overriding a setter — which do you use?
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.
- What is a property wrapper? Can you write a custom one?
A type with wrappedValue (and optionally projectedValue, exposed as $foo, plus init(wrappedValue:)). Writing @Clamped var x makes the compiler store a wrapper… - What is
projectedValue? Give a real example.
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.
- Are property wrappers thread-safe? Is
lazy?
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
- 1.1 · Value vs reference types
- 1.2 · Optionals, pattern matching, control flow
- 1.3 · Protocols, extensions, associated types
- 1.4 · Generics, <code>some</code>, <code>any</code>
- 1.5 · Closures, escaping, capture lists
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch