Switch statement power in Swift - Time & Space Complexity
We want to see how fast a switch statement runs when it checks different cases.
How does the time to find the right case change as we add more cases?
Analyze the time complexity of the following code snippet.
func describeNumber(_ number: Int) -> String {
switch number {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
default:
return "Other"
}
}
This code checks a number and returns a word for 1, 2, or 3, or "Other" if none match.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The compiler optimizes the switch to a jump table lookup or binary search.
- How many times: Constant time: typically 1 lookup, regardless of cases.
The Swift compiler generates efficient code (jump table for dense cases, binary search for sparse), so runtime stays constant.
| Input Size (number of cases) | Approx. Operations (lookups) |
|---|---|
| 3 | 1 lookup |
| 10 | 1 lookup |
| 100 | 1 lookup (or log₂(100) ~7 for sparse) |
Pattern observation: Constant time O(1) for typical cases; does not grow linearly.
Time Complexity: O(1)
This means the time to find the right case is constant, thanks to compiler optimizations like jump tables.
[X] Wrong: "Switch statements check cases one by one like if-else, so O(n)."
[OK] Correct: Swift compiler optimizes switches on integers/enums to jump tables (O(1)) or binary search (O(log n)), not sequential checks.
Understanding switch optimizations shows deep knowledge of language internals and performance, impressing interviewers.
"Swift uses jump tables or binary search for switches. Confirm by checking assembly output. How does this differ from naive if-else?"