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?"
Practice
switch statement in Swift compared to multiple if-else statements?Solution
Step 1: Understand the purpose of switch
The switch statement is designed to check a value against multiple cases clearly and cleanly.Step 2: Compare with if-else statements
While if-else can do similar checks, switch improves readability and maintenance by organizing cases neatly.Final Answer:
It makes the code easier to read and maintain by clearly checking many cases. -> Option BQuick Check:
Switch improves readability = A [OK]
- Thinking switch is always faster than if-else
- Believing switch only works with numbers
- Assuming switch handles errors automatically
switch statement in Swift?Solution
Step 1: Review correct switch syntax
In Swift, a switch statement uses curly braces with cases followed by colons and code blocks.Step 2: Identify the correct option
switch value { case 1: print("One") default: print("Other") } matches the correct syntax: switch value { case 1: ... default: ... }.Final Answer:
switch value { case 1: print("One") default: print("Other") } -> Option DQuick Check:
Correct switch syntax = B [OK]
- Omitting colons after case labels
- Using else instead of default
- Wrong punctuation like arrows or missing braces
let number = 3
switch number {
case 1, 3, 5:
print("Odd")
case 2, 4, 6:
print("Even")
default:
print("Unknown")
}Solution
Step 1: Check the value of number
The variable number is set to 3.Step 2: Match number in switch cases
Case 1, 3, 5 matches number 3, so it prints "Odd".Final Answer:
Odd -> Option AQuick Check:
3 in (1,3,5) = Odd [OK]
- Choosing Even because 3 is odd but not in even case
- Ignoring multiple values in one case
- Assuming default runs when a case matches
let grade = "B"
switch grade {
case "A":
print("Excellent")
case "B"
print("Good")
default:
print("Needs Improvement")
}Solution
Step 1: Check syntax of each case
Each case label must end with a colon (:). The case "B" is missing this colon.Step 2: Confirm other parts are correct
Default case exists, strings are allowed, and print inside switch is valid.Final Answer:
Missing colon after case "B" -> Option CQuick Check:
Case labels need colon = C [OK]
- Forgetting colon after case label
- Thinking default is optional (it is recommended)
- Believing switch can't handle strings
score into grades using a switch statement:- 90 to 100: "A"
- 80 to 89: "B"
- 70 to 79: "C"
- Below 70: "F"
Which switch statement correctly implements this?
Solution
Step 1: Understand range operators
Closed range operator (...) includes both ends, so 90...100 includes 90 and 100.Step 2: Check all ranges cover scores without overlap or gaps
switch score { case 90...100: print("A") case 80...89: print("B") case 70...79: print("C") default: print("F") } uses closed ranges for exact matches (90-100, 80-89, 70-79) and default catches below 70 perfectly without gaps or overlaps.Step 3: Identify issues in other options
B uses half-open ranges (..<) excluding upper bounds like 100 (90..<100 misses 100); C has overlapping ranges (80...90 overlaps 90 with A, 70...80 overlaps 80); D lacks default and doesn't cover all integers (e.g., negatives, >100), causing compile error.Final Answer:
switch score { case 90...100: print("A") case 80...89: print("B") case 70...79: print("C") default: print("F") } -> Option AQuick Check:
Complete, non-overlapping ranges = A [OK]
- Overlapping or missing ranges
- Using half-open ranges that exclude max values
- Not covering all possible values explicitly
Ready to prove it?
Pass the test and this pattern moves unknown
