WrappedValue and projectedValue in Swift - Time & Space Complexity
We want to understand how the time it takes to access and use wrappedValue and projectedValue changes as the program runs.
Specifically, how does the cost grow when these properties are used in Swift property wrappers?
Analyze the time complexity of accessing wrappedValue and projectedValue in this property wrapper example.
@propertyWrapper
struct Wrapper {
var value: Int
var wrappedValue: Int {
get { value }
set { value = newValue }
}
var projectedValue: String {
"Value is \(value)"
}
}
struct Example {
@Wrapper var number: Int
}
This code defines a property wrapper with wrappedValue and projectedValue, then uses it in a struct.
Look for repeated actions when accessing these properties.
- Primary operation: Accessing
wrappedValueorprojectedValuecalls a simple getter or setter. - How many times: Each access is a single operation, no loops or recursion involved.
Accessing wrappedValue or projectedValue always takes the same small number of steps, no matter how many times or what values are involved.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 simple property accesses |
| 100 | 100 simple property accesses |
| 1000 | 1000 simple property accesses |
Pattern observation: The time grows directly with the number of accesses, but each access is quick and constant.
Time Complexity: O(1)
This means each access to wrappedValue or projectedValue takes a fixed amount of time, no matter what.
[X] Wrong: "Accessing projectedValue is slower because it creates a new string every time."
[OK] Correct: While projectedValue may compute a value, this computation is simple and constant time, so it does not grow with input size.
Understanding how property wrappers work under the hood helps you explain performance clearly and confidently in interviews.
What if projectedValue computed a value by looping over a large array? How would the time complexity change?