skip to content

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%

answer

  1. needs mutable storage it owns
  2. local variables, then parameters
  3. no let, computed or top-level
  4. no protocol or extension instance

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.

solid answer

~40 s

A wrapper needs mutable storage it owns, so Swift accepts it on stored `var` properties, `static var`s, local variables since Swift 5.4 and function and closure parameters since Swift 5.5. It rejects `let` ("property wrapper can only be applied to a 'var'"), computed properties, global and top-level variables ("not yet supported in top-level code"), `lazy`, `weak` and `unowned` properties, overrides, and instance properties in a protocol, extension or enum. On a parameter, the body gets `_email` as a `let`, so the wrapped value is read-only unless the setter is `nonmutating`. The wrapper is an implementation detail unless it declares `init(projectedValue:)`, which lets callers pass `$label:`.

code

swift · 29 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 }
}

func register(@Trimmed email: String, @Trimmed name: String) -> String {
    "\(name) <\(email)>"
}

func demo() {
    let greet: (String) -> String = { (@Trimmed name) in "Welcome, \(name)!" }
    @Trimmed var nickname = "  ada  "        // local wrapped variable
    print(register(email: " [email protected] ", name: "\tAda "))
    print(greet("  Grace  "), "[\(nickname)]")
    nickname = " lovelace "
    print("[\(nickname)]")
}
demo()
// Prints "Ada <[email protected]>"
// Prints "Welcome, Grace! [ada]"
// Prints "[lovelace]"

go deeper

for a junior

Recall that a wrapper attribute goes on a var, never on a let or a computed property.

for a middle

List where wrappers are accepted, including locals and parameters, and explain each rejection through the rule that the wrapper owns mutable storage and the accessors.

for a senior

Know the parameter rules: the let backing storage, implementation-detail versus API-level wrappers via init(projectedValue:), and what Swift 6 mode does to wrapped static state.

for a principal

Decide whether wrapped parameters belong in shared APIs, given that an API-level wrapper adds $label: call forms every caller and conformer must understand.

## Where a wrapper attribute is accepted A property wrapper was first designed for stored properties, and Swift has widened where the attribute can go: - **Instance stored `var` properties** of structs and classes, the original use. - **Static stored `var` properties**, including those declared in an extension or an enum. - **Local variables** inside a function or closure, since Swift 5.4: `@Trimmed var nickname = " ada "`. - **Function, method, initializer and closure parameters**, since Swift 5.5: `func register(@Trimmed email: String)`. ## Where the compiler rejects it Each rejection follows from the same model: the wrapper needs its own mutable storage and owns the property's accessors. These are the Swift 6.4 diagnostics: | Declaration | Diagnostic | |---|---| | `@W let b = 1` | `property wrapper can only be applied to a 'var'` | | `@W var c: Int { 1 }` | `property wrapper cannot be applied to a computed property` | | global or top-level `@W var g = 1` | `property wrappers are not yet supported in top-level code` | | `@W lazy var d = 1`, `@W weak var e: K?` | `property 'd' with a wrapper cannot also be lazy` (and `weak`, `unowned`) | | `@W var a: Int { get }` in a protocol | `property 'a' declared inside a protocol cannot have a wrapper` | | instance `@W var` in an extension or enum | `non-static property 'h' declared inside an extension cannot have a wrapper` | | `@W override var k` | `property 'k' with attached wrapper cannot override another property` | | `@W var (f, g) = (1, 2)` | `property wrapper can only apply to a single variable` | The wrapper type has one more restriction: its `wrappedValue` cannot have an `async` or `throws` getter, because the synthesized property must be readable synchronously. In Swift 6 language mode, a wrapped `static var` in a nonisolated type is also rejected as nonisolated global shared mutable state; isolating the enclosing type to `@MainActor` is one way to make it compile. ## Wrappers on parameters A wrapped parameter, `func register(@Trimmed email: String)`, gives the function body three local names, mirroring a property: 1. `_email`, a **`let`** holding the wrapper, built by calling `Trimmed(wrappedValue:)` with the argument. 2. `email`, a computed local that reads `_email.wrappedValue`. It has a setter only if the wrapper's setter is `nonmutating`, so with `Trimmed`, whose setter is mutating, `email = "x"` fails with `cannot assign to value: 'email' is immutable`. 3. `$email`, if the wrapper declares a `projectedValue` with a nonmutating getter. By default such a wrapper is an **implementation detail**: callers pass a plain `String`, the function type stays `(String, String) -> String`, and an unapplied reference such as `register(email:name:)` still has that type. A function with a wrapped parameter can therefore satisfy a protocol requirement written without the wrapper. A wrapper becomes **API-level** when it declares `init(projectedValue:)` directly in its type and the attribute carries no arguments. Callers can then pass either the wrapped value or, with a `$`-prefixed label, a projection: ```swift @propertyWrapper struct Clamped { let range: ClosedRange<Int> private var value: Int init(wrappedValue: Int, _ range: ClosedRange<Int> = 0...100) { self.range = range value = min(max(wrappedValue, range.lowerBound), range.upperBound) } init(projectedValue: Clamped) { self = projectedValue } var wrappedValue: Int { value } var projectedValue: Clamped { self } } func setVolume(@Clamped to level: Int) { print(level, $level.range) } setVolume(to: 140) // Prints "100 0...100" setVolume($to: Clamped(wrappedValue: 7, 0...5)) // Prints "5 0...5" ``` Adding attribute arguments, such as `@Clamped(0...10) to level: Int`, turns the wrapper back into an implementation detail, and a `$to:` call then fails with `cannot use property wrapper projection argument`. ## Closures and local variables - In a closure, write the attribute inside the parameter list: `{ (@Trimmed name) in ... }`. The closure's type is still `(String) -> String`. - A wrapped local variable behaves like a wrapped property: `nickname = " lovelace "` runs the wrapper's setter, and `_nickname` is the local storage. ## Why these limits exist - A `let` or computed declaration has no mutable storage for the wrapper to own. - A protocol requirement and an instance property in an extension or enum cannot add stored state. - `lazy`, `weak` and `unowned` are themselves storage strategies that would compete with the wrapper's. - Top-level and global variables have not been implemented yet; the diagnostic says "not yet".

  • Inside func register(@Trimmed email: String), why can't the body assign email = "x"?
    The backing `_email` is a `let`, and `email` is a computed local over `_email.wrappedValue`. A setter is synthesized only when the wrapper's setter is `nonmutating`; `Trimmed` is a struct with a mutating setter, so Swift reports that `email` is immutable. This matches ordinary parameters, which are constants too.
  • When can a caller write setVolume($to: someClamped) instead of setVolume(to: 140)?
    Only when the wrapper declares `init(projectedValue:)` directly in its type and the attribute has no arguments. That makes the wrapper API-level: Swift calls `init(wrappedValue:)` for a plain `to:` argument and `init(projectedValue:)` for `$to:`. With attribute arguments the wrapper stays an implementation detail and a `$to:` argument is rejected.

  • Property wrappers work on let constants as long as the wrapper is a struct.
  • A global var can carry a wrapper if the file is not main.swift.
  • A wrapped parameter changes the function's type to take the wrapper type.
  • Assigning to a wrapped parameter inside the function updates the caller's variable.
  • Protocols can require a wrapped property such as @Trimmed var email: String { get }.

Assumes Swift 6.4: wrappers on local variables arrived in Swift 5.4 and on parameters in Swift 5.5, and Swift 6 language mode rejects a wrapped static var as nonisolated global mutable state.