skip to content

Property Wrappers

A property wrapper moves get and set logic into a reusable type with a wrappedValue and an optional $ projection. Interviewers ask how framework wrappers work and how to write one.

on this pageshow

explore

questions

5

In Swift, what must a @propertyWrapper type declare, and what does the compiler generate when you write @Trimmed var email: String?

level: juniorimportance: must knowfreq 72%

answer

  1. one required member on the type
  2. same access level as the wrapper
  3. private storage with a leading underscore
  4. a computed property forwards get and set

basics

~20 s

A @propertyWrapper type must declare a non-static wrappedValue property. For @Trimmed var email, Swift synthesizes private storage _email of type Trimmed and turns email into a computed property that forwards get and set to _email.wrappedValue.

solid answer

~40 s

The only requirement is a non-static `wrappedValue` property with the same access level as the wrapper type; it can be stored or computed, and the wrapper's initializers may not be failable. When I write `@Trimmed var email: String`, the compiler adds a `private var _email: Trimmed` holding the wrapper instance and makes `email` a computed `String` whose getter reads `_email.wrappedValue` and whose setter writes it. So every read and write runs the wrapper's code, and I can't add my own `get` or `set` to `email`. An `= value` on the declaration becomes a call to `init(wrappedValue:)`, so that initializer must apply the same transformation as the setter, or the first value slips through untouched.

code

swift · 26 lines
swift
@propertyWrapper
struct Trimmed {
    private var text = ""

    var wrappedValue: String {
        get { text }
        set {
            let head = newValue.drop(while: \.isWhitespace)
            text = String(head.reversed().drop(while: \.isWhitespace).reversed())
        }
    }

    init(wrappedValue: String) {
        self.wrappedValue = wrappedValue   // runs the setter, so the first value is trimmed too
    }
}

struct SignUpForm {
    @Trimmed var email: String
    @Trimmed var displayName = ""
}

var form = SignUpForm(email: "  [email protected] ")
form.displayName = "\tAda  "
print("[\(form.email)] [\(form.displayName)]")
// Prints "[[email protected]] [Ada]"

go deeper

for a junior

Recall the single requirement, a non-static wrappedValue, and that @Name on a var routes its reads and writes through an instance of that type.

for a middle

Explain the synthesized pair: private _email storage of the wrapper type plus a computed email forwarding to wrappedValue, and which initializer each declaration form calls.

for a senior

Show you know where wrappers leak: the first value arrives through init(wrappedValue:), not the setter, and a class wrapper makes copies of the containing struct share state.

for a principal

Judge when a wrapper earns its place over a plain computed property or a dedicated type, given that it hides storage and accessors from readers of the declaring type.

## What a property wrapper is A **property wrapper** is an ordinary Swift `struct`, `enum` or `class` marked with the `@propertyWrapper` attribute. Marking the type creates a **custom attribute** with the same name, so a type called `Trimmed` can be written as `@Trimmed` in front of a variable. The wrapper moves the get and set logic that would otherwise be copied onto every property (trimming input, clamping a number, logging writes) into one reusable type. The property that carries the attribute is called the **wrapped property**; the value it exposes is the **wrapped value**. ## The one requirement: `wrappedValue` The compiler checks a short list of rules on the wrapper type itself: - It must declare an **instance (non-static) property named `wrappedValue`**. Without one, Swift reports `property wrapper type 'Trimmed' does not contain a non-static property named 'wrappedValue'`. - `wrappedValue` must have the **same access level as the wrapper type**. A `public` wrapper with an `internal` `wrappedValue` is rejected. - **No initializer of the wrapper may be failable**: `init?(wrappedValue:)` is an error. - If an initializer has a `wrappedValue` parameter, that parameter's type must equal the `wrappedValue` property's type, or be an `@autoclosure` of it. `wrappedValue` can be stored or computed. Most real wrappers keep private storage and make `wrappedValue` computed, so the setter can transform what is written: ```swift @propertyWrapper struct Uppercased { private var text = "" var wrappedValue: String { get { text } set { text = newValue.uppercased() } } } ``` Everything else (`projectedValue`, extra initializers, methods) is optional. ## What the compiler generates for `@Trimmed var email: String` Writing `@Trimmed var email: String` inside `SignUpForm` makes the compiler synthesize two declarations: 1. A **stored property `_email` of type `Trimmed`**, the wrapper instance itself. Its access level is always `private`. 2. A **computed property `email` of type `String`** whose getter returns `_email.wrappedValue` and whose setter assigns `_email.wrappedValue = newValue`. The wrapper is responsible for storing the value; the compiler only adds storage for the wrapper instance and the forwarding accessors. The hand-written equivalent looks like this: ```swift struct SignUpFormByHand { private var _email: Trimmed var email: String { get { _email.wrappedValue } set { _email.wrappedValue = newValue } } init(email: String) { _email = Trimmed(wrappedValue: email) } } ``` Because `email` is now computed, you cannot add your own `get` or `set` to a wrapped property; the wrapper owns them. ## How the wrapper instance gets created The declaration decides which initializer of the wrapper Swift calls to build `_email`: | Declaration | Wrapper initializer Swift calls | |---|---| | `@Trimmed var email: String` (no value) | `init()` if the wrapper has one; otherwise the struct's initializer must supply the value | | `@Trimmed var displayName = ""` | `init(wrappedValue: "")` | | `@Clamped(0...100) var volume = 50` | `init(wrappedValue: 50, 0...100)` | | `@Clamped(wrappedValue: 50, 0...100) var volume: Int` | `init(wrappedValue:_:)` with those exact arguments | An `=` initial value is sugar for the `wrappedValue:` argument. It goes to the initializer, **not** through the setter, which is why the `Trimmed` example assigns `self.wrappedValue = wrappedValue` inside `init(wrappedValue:)`: that line runs the trimming setter for the first value too. How a wrapper reshapes a struct's memberwise initializer is a separate rule with its own surprises. ## Walking through the sign-up form In the code example, `SignUpForm(email: " [email protected] ")` builds `_email` with `Trimmed(wrappedValue:)`, which trims on the way in. Later, `form.displayName = "\tAda "` calls the synthesized setter, which calls `Trimmed`'s `wrappedValue` setter, which trims again. Every read goes through the getter and returns the clean string. The form type contains no trimming code at all; adding a third trimmed field is one attribute. ## Common mistakes - Expecting a protocol: there is no `PropertyWrapper` protocol to conform to; the attribute plus the `wrappedValue` member is the whole contract. - Reaching for `_email` from outside the type: it is `private`, so only the type's own declaration and its same-file extensions can touch it. - Applying the attribute to a `let` or a computed property: the compiler rejects both, because the wrapper needs mutable storage and owns the accessors. - Storing the initial value directly into private storage in `init(wrappedValue:)` and so skipping the transformation for the first value.

  • Why does Trimmed's init(wrappedValue:) assign self.wrappedValue instead of the private text property?
    An `= value` on a wrapped property, or the memberwise argument, reaches the wrapper through `init(wrappedValue:)`, not through the `wrappedValue` setter. Assigning `self.wrappedValue` after `text` has its default runs the setter, so the first value is trimmed exactly like later writes. Writing `text = wrappedValue` would store the untrimmed string until the next assignment.
  • Can a property wrapper be a class, and what changes if it is?
    Yes: a `struct`, `enum` or `class` can carry `@propertyWrapper`. With a class wrapper the synthesized setter is `nonmutating`, so you can assign the wrapped property through a `let` instance of the containing struct, and copies of that struct share one wrapper object, so a write through one copy shows up in the other.
  • What does the compiler say if the wrapper's wrappedValue is declared static?
    It reports that the property wrapper type does not contain a non-static property named `wrappedValue`. The value belongs to each wrapped property, so it must be an instance property; a `static` member would be shared by every property the wrapper is applied to.

A wrapped property is like a building's mail room: residents still use their own address, but every parcel in or out passes the same desk, which applies one set of rules for the whole building.

  • A property wrapper type must conform to a PropertyWrapper protocol.
  • The wrapped property stores the String itself and the wrapper only validates it.
  • Code outside the type can read _email to reach the wrapper instance.
  • init(wrappedValue:) can be failable to reject bad input at declaration time.
  • An initial value written with = goes through the wrappedValue setter.
open as a page

In a Swift property wrapper, what is projectedValue, and how do $volume and _volume differ from volume?

level: middleimportance: must knowfreq 62%

basics

~10 s

projectedValue is an optional property a wrapper declares to expose extra information; Swift surfaces it as $volume with volume's access level. volume forwards to wrappedValue, and _volume is the private wrapper instance itself.

open as a page

In Swift, which declarations besides stored properties can carry a property wrapper attribute, and which ones does the compiler reject?

level: middleimportance: should knowfreq 38%

basics

~20 s

Besides stored var properties, wrappers work on static vars, local variables (Swift 5.4) and function and closure parameters (Swift 5.5). The compiler rejects them on let, computed, global, lazy, weak and overriding properties, and protocol or extension instance properties.

open as a page

In Swift, why does stacking @Trimmed @Lowercased on a String property fail to compile, and how do stacked property wrappers nest?

level: seniorimportance: should knowfreq 28%

basics

~10 s

Stacked wrappers nest, with the first attribute outermost, so @Trimmed @Lowercased needs Trimmed's wrappedValue to hold a Lowercased; Trimmed's is a String, so it fails. A generic outer wrapper, such as Counted<Value>, composes fine.

open as a page

A Swift AudioSettings struct changes @Clamped(0...100) var volume = 50 to @Clamped(wrappedValue: 50, 0...100) var volume: Int; why does AudioSettings(volume: 70) stop compiling?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The memberwise parameter takes Int only when volume has an = initial value, or no value and no attribute arguments; spelling wrappedValue: inside the attribute makes the parameter Clamped, so passing 70 no longer type-checks.

open as a page