Enum methods and computed properties in Swift - Time & Space Complexity
We want to understand how the time it takes to run enum methods and computed properties changes as the enum grows.
How does the number of enum cases affect the work done inside its methods or computed properties?
Analyze the time complexity of the following code snippet.
enum Direction {
case north, south, east, west
func opposite() -> Direction {
switch self {
case .north: return .south
case .south: return .north
case .east: return .west
case .west: return .east
}
}
var isVertical: Bool {
self == .north || self == .south
}
}
This enum has methods and computed properties that return values based on the current case.
Look for loops or repeated checks inside the methods or properties.
- Primary operation: The switch statement or equality checks dispatch to the matching case efficiently.
- How many times: Constant time (O(1)) per method call or property access, regardless of case count.
The work done does not grow with the number of cases. Swift optimizes enum switches using jump tables or direct dispatch for constant-time execution.
| Input Size (number of enum cases) | Approx. Operations |
|---|---|
| 4 | 1 dispatch |
| 10 | 1 dispatch |
| 100 | 1 dispatch |
Pattern observation: Operations remain constant independent of the number of enum cases.
Time Complexity: O(1)
This means the execution time is constant, even as the number of enum cases increases.
[X] Wrong: "Switch statements on enums check cases linearly, so O(n) where n is case count."
[OK] Correct: Swift compiler optimizes exhaustive switches on enums to constant-time dispatch (e.g., jump tables), not linear search.
Knowing enum methods and properties run in O(1) time demonstrates understanding of compiler optimizations and performance characteristics of Swift data structures.
"What if we replaced the switch with a dictionary lookup? How would the time complexity change? (Hint: Still O(1) average case, but with overhead.)"