What is a property wrapper? Can you write a custom one?

1.6.3 · L2 · Interview

Mental model. A property wrapper is a tiny vending machine bolted over a drawer: every read and write goes through its rules.

A type with wrappedValue (and optionally projectedValue, exposed as $foo, plus init(wrappedValue:)). Writing @Clamped var x makes the compiler store a wrapper instance and route get/set through it.

Custom wrappers are ordinary Swift: @Clamped, @UserDefault, @Atomic. The stdlib and SwiftUI use them heavily: @State, @Binding, @Published, @AppStorage.

Contrast with @Observable: that is a macro generating accessors at compile time, not a wrapper.

Common traps

  • Calling @Observable a property wrapper. It is a macro. A very common trick question.
  • Adding a wrapper to a computed property. Wrappers need storage; you cannot wrap a property that already has a get/set.

They might follow up with

  • Can a wrapper be generic and constrained? Yes, and it can have multiple init overloads for different call sites.
  • What is the performance cost? Usually zero at -O once inlined, but wrappers can block some optimizations and add a stored instance per property.

Related questions

  • 1.6.4 What is projectedValue? Give a real example.
  • 1.10.3 Macros vs property wrappers vs result builders — one sentence each.
  • 1.6.2 Property observers vs overriding a setter — which do you use?

← Property observers vs overriding a setter — which do you use?   What is projectedValue? Give a real example. →