No implicit fallthrough in switch in Swift - Time & Space Complexity
We want to understand how the time it takes to run a switch statement changes as we add more cases.
Specifically, does adding more cases make the program slower, and how much slower?
Analyze the time complexity of the following code snippet.
let value = 3
switch value {
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case 4:
print("Four")
default:
print("Other")
}
This code checks the value and prints a message depending on which case matches.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement compares the input value to each case until it finds a match.
- How many times: In the worst case, it checks each case once until it finds the right one or reaches default.
As the number of cases increases, the number of comparisons grows roughly in a straight line.
| Input Size (number of cases) | Approx. Comparisons |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The time to find the matching case grows linearly with the number of cases.
Time Complexity: O(n)
This means the time to run the switch grows in direct proportion to the number of cases.
[X] Wrong: "Switch statements always run in constant time no matter how many cases there are."
[OK] Correct: In Swift, the switch checks cases one by one until it finds a match, so more cases mean more checks and longer time.
Understanding how switch statements scale helps you write efficient code and explain your choices clearly in interviews.
"What if the switch used pattern matching with ranges instead of individual cases? How would the time complexity change?"