Switch must be exhaustive in Swift - Time & Space Complexity
We want to see how the time it takes to run a switch statement changes as the number of cases grows.
How does adding more cases affect the work the program does?
Analyze the time complexity of the following code snippet.
enum Direction {
case north, south, east, west
}
func move(_ direction: Direction) {
switch direction {
case .north:
print("Moving north")
case .south:
print("Moving south")
case .east:
print("Moving east")
case .west:
print("Moving west")
}
}
This code uses a switch to handle all possible directions in an enum. The switch is exhaustive, covering every case, allowing compiler optimizations.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement dispatches directly to the matching case.
- How many times: Constant time (1 operation), no repetition regardless of cases.
Swift compiler optimizes exhaustive switches on enums using jump tables or direct indexing, making execution constant time.
| Input Size (number of cases) | Approx. Operations |
|---|---|
| 4 | 1 operation |
| 10 | 1 operation |
| 100 | 1 operation |
Pattern observation: Operations remain constant, independent of cases.
Time Complexity: O(1)
The time is constant due to compiler optimizations like jump tables for exhaustive enums.
[X] Wrong: "Switch statements check cases sequentially, so O(n)."
[OK] Correct: Compilers generate efficient code (jump tables, hash tables), not linear scans. Exhaustive switches enable perfect optimization.
Knowing switch optimizations demonstrates understanding of compiler behavior and efficient code generation.
"What if the switch used a default case instead of listing all cases? How would that affect the time complexity?"