Enum with switch pattern matching in Swift - Time & Space Complexity
When using enums with switch pattern matching, it's important to know how the program's work grows as the number of cases increases.
We want to understand how the time to decide which case matches changes with more enum cases.
Analyze the time complexity of the following code snippet.
enum Direction {
case north
case south
case east
case west
}
func describe(direction: Direction) -> String {
switch direction {
case .north: return "Going north"
case .south: return "Going south"
case .east: return "Going east"
case .west: return "Going west"
}
}
This code matches an enum value using a switch to return a description string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement performs a direct jump to the matching case.
- How many times: Always constant time (1 operation), regardless of the number of cases.
Swift compilers optimize enum switches using jump tables or perfect hashing, making lookup constant time even as cases grow.
| Input Size (n) | Approx. Operations |
|---|---|
| 4 | 1 jump |
| 10 | 1 jump |
| 100 | 1 jump |
Pattern observation: The number of operations stays constant regardless of enum cases.
Time Complexity: O(1)
This means the time to find the matching case is constant, independent of the number of enum cases.
[X] Wrong: "Switch statements check cases one by one linearly, so O(n)."
[OK] Correct: Compilers optimize switches on enums to O(1) using jump tables, not sequential checks.
Knowing switch optimizations shows deep understanding of compiler behavior and why enums + switch are efficient for dispatching.
"What if we replaced the switch with a dictionary lookup from enum rawValue to string? How would the time complexity change?"
Answer: Still O(1) average case, but switch is often faster due to no hashing/dynamic lookup.