skip to content

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%

answer

  1. first attribute is the outer layer
  2. storage type nests generic arguments
  3. outer wrappedValue holds the inner wrapper
  4. only one dollar projection survives

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.

solid answer

~30 s

Swift composes wrappers by nesting: in `@A @B var x: T` the storage `_x` is `A<B<T>>` and the accessors go through `_x.wrappedValue.wrappedValue`. So the outer wrapper's `wrappedValue` must be able to hold the inner wrapper. `Trimmed` and `Lowercased` each declare `wrappedValue: String`, so in either order the compiler reports "composed wrapper type 'Lowercased' does not match type of 'Trimmed.wrappedValue', which is 'String'". `@Counted @Trimmed` works because `Counted<Value>` is generic, and only the outer `Counted`'s projection becomes `$email`. To trim and lowercase together I'd write one normalizing wrapper rather than stack two String-only ones.

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 }
}

@propertyWrapper
struct Counted<Value> {
    var wrappedValue: Value { didSet { writes += 1 } }
    private(set) var writes = 0
    var projectedValue: Int { writes }
    init(wrappedValue: Value) { self.wrappedValue = wrappedValue }
}

struct SignUpForm {
    @Counted @Trimmed var email = ""   // _email is Counted<Trimmed>
}

var form = SignUpForm()
form.email = "  [email protected] "
form.email = " [email protected]"
print("[\(form.email)]", form.$email)   // Prints "[[email protected]] 2"

go deeper

for a junior

Recall that several wrapper attributes can sit on one property and that their order matters.

for a middle

Explain the nesting: first attribute outermost, storage typed A<B<T>>, accessors through two wrappedValue levels, and only the outer projection as $name.

for a senior

Read a composition error and fix it by choosing a generic outer wrapper or merging two value transformations into one wrapper, and explain why the outer layer never sees the raw value.

for a principal

Decide whether a codebase allows stacked custom wrappers at all, given that their order changes behaviour and some wrong orders still compile.

## How stacking works Swift lets you put more than one wrapper attribute on a property. The wrappers are **nested, not chained side by side**: the **first** attribute is the **outermost** wrapper, and each later attribute is wrapped inside it, with the property's own type at the centre. For ```plaintext @Counted @Trimmed var email = "" ``` the private storage `_email` has type `Counted<Trimmed>`, and the synthesized accessors reach through both levels: ```swift struct SignUpFormByHand { private var _email = Counted(wrappedValue: Trimmed(wrappedValue: "")) var email: String { get { _email.wrappedValue.wrappedValue } set { _email.wrappedValue.wrappedValue = newValue } } var emailWrites: Int { _email.projectedValue } // what $email reads } ``` Three consequences follow directly from that shape: - The **outer wrapper's `wrappedValue` holds the inner wrapper**, not the `String`. `Counted<Value>` works as the outer layer only because it is generic over `Value`, so `Value` can be `Trimmed`. - The `=` initial value is threaded inward: `Counted(wrappedValue: Trimmed(wrappedValue: ""))`, one `init(wrappedValue:)` per layer. - Only the **outermost** wrapper's `projectedValue` becomes `$email`. Here `$email` is `Counted`'s write count; `Trimmed` has no projection of its own anyway, and an inner projection would not be reachable through `$` either. ## Why `@Trimmed @Lowercased` fails `Trimmed` and `Lowercased` are both written for one type: each declares `var wrappedValue: String`. Stacking them asks for storage of type `Trimmed` whose `wrappedValue` is a `Lowercased`, which `Trimmed` cannot hold. The Swift 6.4 compiler says so directly: ```plaintext SignUpForm.swift:20:15: error: cannot convert value of type 'Lowercased' to specified type 'String' SignUpForm.swift:20:15: error: composed wrapper type 'Lowercased' does not match type of 'Trimmed.wrappedValue', which is 'String' ``` Swapping the order does not help, because `Lowercased` is just as fixed to `String`. Composition is **not commutative**: the order decides the nesting, and only orders in which every outer wrapper can hold the next wrapper type type-check at all. ## Ways to fix it 1. **Make the outer wrapper generic** over its value, as `Counted<Value>` is. This works for wrappers that do not need to inspect the value, such as counting or logging writes. 2. **Write one wrapper that does both jobs**, for example a `NormalizedEmail` wrapper that trims and lowercases in a single setter. For two transformations of the same `String`, this is usually the clearest result. 3. **Compose functions, not wrappers**: give a single wrapper a list of transformations to apply in order. A generic outer wrapper is never handed the `String`: its setter receives a `Trimmed` value. That is the real composition limit: an outer layer sees the inner wrapper, not the text. ## What happens on each write With `@Counted @Trimmed var email`, assigning `form.email = " [email protected] "` runs in this order: 1. The synthesized setter reads `_email.wrappedValue`, a copy of the inner `Trimmed`. 2. It assigns that copy's `wrappedValue`, so `Trimmed`'s setter trims the string. 3. It writes the modified `Trimmed` back to `_email.wrappedValue`, so `Counted`'s `didSet` fires and increments the count. That write-back is why `Counted` sees every assignment, and why the code example prints a count of 2 after two writes. The value set during initialization does not count, because `Counted`'s `didSet` does not run when its own initializer assigns `wrappedValue`. ## Initializers and the memberwise parameter Composition does not change how the declaring struct is built from outside. Because `@Counted @Trimmed var email = ""` has an `=` initial value, the memberwise initializer still takes `email: String = ""`, and `SignUpForm(email: " x ")` runs `Trimmed(wrappedValue:)` and then `Counted(wrappedValue:)`, innermost first, before `_email` is stored. Code that builds the form never sees either wrapper type, which is what makes a stacked declaration easy to add and easy to misread: the order is visible only in the attribute list. ## Composition limits worth naming - Wrapper mutability composes too: an inner wrapper with a `mutating` getter cannot sit inside an outer wrapper whose `wrappedValue` is get-only, and the compiler reports exactly that combination. - On a wrapped function parameter, a `$label:` argument initializes only the outermost wrapper through `init(projectedValue:)`, while a plain argument runs `init(wrappedValue:)` once per layer. - Some semantically wrong orders still type-check, for example two generic wrappers in the order you did not intend, so the order deserves a comment in review.

  • In @Counted @Trimmed var email, why does Counted's didSet fire on every assignment?
    The synthesized setter reads `_email.wrappedValue`, mutates that inner `Trimmed`'s `wrappedValue`, and writes the inner wrapper back to `_email.wrappedValue`. That write-back is a set on `Counted`'s property, so its observer runs once per assignment, after `Trimmed` has trimmed the text.
  • Why can't the outer Counted wrapper also validate the email text?
    Its setter receives a `Trimmed` value, because the outer layer's `wrappedValue` holds the inner wrapper. Generic code over `Value` cannot read the string inside without knowing it is `Trimmed`. Validation that needs the text belongs in the innermost wrapper or in a single combined wrapper.

  • Stacked wrappers apply as a flat pipeline, each seeing the String.
  • The last attribute written is the outermost wrapper.
  • Swapping the two attributes fixes a type mismatch between String-only wrappers.
  • Each stacked wrapper gets its own $ projection on the property.
  • Composition order never matters as long as the code compiles.