Enum declaration and cases in Swift - Time & Space Complexity
Enums group related values together in Swift. We want to see how the time to create or use enums changes as we add more cases.
How does the number of enum cases affect the work the program does?
Analyze the time complexity of the following code snippet.
enum Direction {
case north
case south
case east
case west
}
func printDirection(_ dir: Direction) {
switch dir {
case .north: print("Going north")
case .south: print("Going south")
case .east: print("Going east")
case .west: print("Going west")
}
}
This code defines an enum with four directions and a function that prints a message based on the direction.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement directly jumps to the matching enum case using a compiler-optimized jump table.
- How many times: Constant time (O(1)), independent of the number of enum cases.
As the number of enum cases grows, the switch execution time remains constant due to compiler optimizations like jump tables.
| Input Size (n) | Approx. Operations |
|---|---|
| 4 | 1 |
| 10 | 1 |
| 100 | 1 |
Pattern observation: The number of operations is constant regardless of the number of enum cases.
Time Complexity: O(1)
This means the time to find the matching case is constant regardless of the number of enum cases.
[X] Wrong: "Switching on enums checks cases one by one, taking time proportional to the number of cases."
[OK] Correct: Swift compiler optimizes simple enum switches to constant time using jump tables or direct dispatch.
Understanding how enum case checks grow helps you explain how your code handles different options efficiently.
"What if we replaced the switch with a dictionary lookup for enum cases? How would the time complexity change?"