Composing property wrappers in Swift - Time & Space Complexity
When we combine property wrappers in Swift, it's important to see how the work done grows as we use more wrappers or properties.
We want to know how the time to access or set a property changes when wrappers are composed.
Analyze the time complexity of the following code snippet.
@propertyWrapper
struct WrapperA {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperB {
var wrappedValue: Int
}
struct Example {
@WrapperA @WrapperB var number: Int
}
This code composes two property wrappers on one property, layering their behavior.
Look for repeated actions when accessing or setting the property.
- Primary operation: Accessing or setting the wrappedValue goes through each wrapper in order.
- How many times: Once per wrapper, so two times here.
As you add more wrappers, each access or set runs through all wrappers one by one.
| Number of Wrappers (n) | Approx. Operations |
|---|---|
| 1 | 1 |
| 5 | 5 |
| 10 | 10 |
Pattern observation: The work grows directly with the number of wrappers, one after another.
Time Complexity: O(n)
This means the time to get or set the property grows linearly with how many wrappers you compose.
[X] Wrong: "Composing multiple wrappers happens all at once, so time stays the same."
[OK] Correct: Each wrapper adds a step to access or set, so the time adds up, not stays flat.
Understanding how composing wrappers affects time helps you explain performance in real Swift code, showing you know how layering features impacts speed.
"What if each wrapper added extra work inside its getter or setter? How would that change the time complexity?"