Property wrappers with configuration in Swift - Time & Space Complexity
When using property wrappers with configuration, it's important to see how the code runs as the input or usage grows.
We want to know how the time to set or get a wrapped property changes when we use different configurations.
Analyze the time complexity of the following Swift property wrapper with configuration.
@propertyWrapper
struct Clamped {
private var value: Int
private let range: ClosedRange
init(wrappedValue: Int, _ range: ClosedRange) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
}
struct Example {
@Clamped(0...10) var number: Int = 5
}
This code defines a property wrapper that clamps an integer within a range, configured when used.
Look for operations that repeat or scale with input.
- Primary operation: The clamping calculation using min and max functions.
- How many times: Each time the wrapped property is set, the clamp runs once.
The clamping calculation always does a fixed number of steps regardless of the value size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 (min, max, assignment) |
| 100 | 3 (same fixed steps) |
| 1000 | 3 (still fixed steps) |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the time to set or get the property does not grow with input size; it stays constant.
[X] Wrong: "The clamping will take longer if the range is bigger or the value is larger."
[OK] Correct: The clamp uses simple comparisons that always take the same time, no matter the numbers involved.
Understanding how property wrappers work with configuration helps you explain how code behaves as it runs, a key skill in many coding discussions.
"What if the property wrapper performed a loop over an array inside the setter? How would the time complexity change?"