@propertyWrapper declaration in Swift - Time & Space Complexity
We want to understand how the time it takes to use a @propertyWrapper grows as we use it more in code.
Specifically, how does the cost change when we access or set wrapped properties many times?
Analyze the time complexity of the following code snippet.
@propertyWrapper
struct Capitalized {
private var value: String = ""
init(wrappedValue: String) {
self.wrappedValue = wrappedValue
}
var wrappedValue: String {
get { value }
set { value = newValue.capitalized }
}
}
struct Person {
@Capitalized var name: String
}
var p = Person(name: "john doe")
print(p.name)
p.name = "jane smith"
print(p.name)
This code defines a property wrapper that capitalizes strings when set, then uses it in a struct.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Capitalizing the string when setting the wrapped property.
- How many times: Each time the property is set, the capitalization runs once on the new string.
Each time we set the property, the capitalization processes the whole string once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (characters) | 10 operations to capitalize |
| 100 (characters) | 100 operations to capitalize |
| 1000 (characters) | 1000 operations to capitalize |
Pattern observation: The time grows linearly with the length of the string being set.
Time Complexity: O(n)
This means the time to set the property grows in direct proportion to the string length.
[X] Wrong: "Setting the property is always a quick, fixed-time action regardless of string size."
[OK] Correct: Because the wrapper modifies the string by capitalizing it, the time depends on how long the string is.
Understanding how property wrappers affect performance helps you write clean code without surprises in speed as data grows.
"What if the property wrapper performed a more complex operation, like sorting an array, instead of capitalizing a string? How would the time complexity change?"