Custom validation property wrappers in Swift - Time & Space Complexity
When using custom validation property wrappers, it is important to understand how the time to validate grows as the input changes.
We want to know how the validation work scales when the wrapped value changes size or complexity.
Analyze the time complexity of the following Swift property wrapper that validates a string's length.
@propertyWrapper
struct LengthValidated {
private var value: String = ""
let maxLength: Int
var wrappedValue: String {
get { value }
set {
if newValue.count <= maxLength {
value = newValue
}
}
}
}
This code checks if a new string fits within a maximum length before storing it.
Look for operations that repeat or scale with input size.
- Primary operation: Counting characters in the new string (newValue.count)
- How many times: Once each time the wrapped value is set
The time to count characters grows as the string gets longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character counts |
| 100 | 100 character counts |
| 1000 | 1000 character counts |
Pattern observation: The work grows directly with the string length.
Time Complexity: O(n)
This means the time to validate grows linearly with the length of the string being set.
[X] Wrong: "Counting characters is always a constant time operation."
[OK] Correct: In Swift, counting characters can take time proportional to the string length because of how characters are encoded.
Understanding how validation scales helps you write efficient property wrappers and shows you can reason about performance in real code.
"What if the validation also checked for forbidden characters by scanning the string? How would the time complexity change?"