Skip to Content
Course content

139: Composing Multiple Property Wrappers

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, why can't I just stack two property wrappers on one variable?

If you've tried this already, you've probably seen the compiler scream at you. You might think it makes sense to do something like @Trimmed @Capitalized var username: String, but Swift just doesn't work that way. The language design currently only allows one property wrapper per property.

I'll be honest: it's a bit frustrating. We want a pipeline—first trim the whitespace, then capitalize the result—but Swift sees that second @ and doesn't know how to chain the wrappedValue getters and setters together. To get around this, we have to build a "Composite" wrapper. Essentially, we create a third wrapper whose sole job is to manage the other two.

How do I actually build a composite wrapper?

The trick is to instantiate your existing wrappers as private properties inside the new one. You aren't using them as property wrappers in the traditional sense (with the @ symbol) inside the composite; you're using them as regular types.

Let's say we have a @Trimmed wrapper and a @Capitalized wrapper. Here is how I would compose them into a single @CleanName wrapper:

struct Trimmed {
    var wrappedValue: String {
        get { _value }
        set { _value = newValue.trimmingCharacters(in: .whitespaces) }
    }
    private var _value: String = ""
}

struct Capitalized {
    var wrappedValue: String {
        get { _value }
        set { _value = newValue.capitalized }
    }
    private var _value: String = ""
}

@propertyWrapper
struct CleanName {
    // We wrap the wrappers
    private var trimmed = Trimmed()
    private var capitalized = Capitalized()

    var wrappedValue: String {
        get {
            // Pass the value through the chain
            return capitalized.wrappedValue
        }
        set {
            // First trim it, then capitalize it
            trimmed.wrappedValue = newValue
            capitalized.wrappedValue = trimmed.wrappedValue
        }
    }
}

struct UserProfile {
    @CleanName var name: String
}

var profile = UserProfile()
profile.name = "  john doe  " 
print(profile.name) // "John Doe"

Notice that the set block is where the magic happens. I'm manually piping the data from the input, through the Trimmed logic, and finally into the Capitalized logic. It's a manual chain, but it gives you total control over the order of operations.

What happens to the projected value?

If your individual wrappers use projectedValue (the $ syntax), you can't automatically "inherit" them. The composite wrapper acts as a wall. If you want to access the projected value of one of the internal wrappers, you have to explicitly define a projectedValue in your composite wrapper and decide which internal wrapper it should expose.

For example, if Trimmed had a projected value that returned the original untrimmed string, your CleanName wrapper would need to look like this:

@propertyWrapper
struct CleanName {
    private var trimmed = Trimmed()
    private var capitalized = Capitalized()

    var wrappedValue: String {
        get { capitalized.wrappedValue }
        set { 
            trimmed.wrappedValue = newValue
            capitalized.wrappedValue = trimmed.wrappedValue 
        }
    }

    // Explicitly forwarding the projection to the trimmed wrapper
    var projectedValue: String {
        return trimmed.projectedValue
    }
}

I usually recommend keeping composite wrappers simple. If you find yourself needing to project values from three different internal wrappers, you're probably fighting the language. At that point, it might be cleaner to just write a single, dedicated property wrapper that handles all the logic in one place rather than trying to glue smaller ones together.




📋 Practical Task

Building a Validated and Sanitized Username Field

You need to create a composite property wrapper called @Username. This wrapper should combine the logic of two existing wrappers: @Trimmed (which removes whitespace) and @MinLength (which ensures a string is at least 3 characters long, otherwise returning a default value of "Invalid").

  • Implement the Trimmed wrapper.
  • Implement the MinLength wrapper (it should take an Int as an argument for the minimum length).
  • Create the @Username composite wrapper that first trims the input and then applies the minimum length validation.
  • Test it by creating a User struct with a @Username var handle: String property. Verify that " ab " results in "Invalid" and " swiftie " results in "swiftie".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.