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.
Practice
enum with associated values in Swift?Solution
Step 1: Understand enum basics
An enum groups related values under one type, making code organized.Step 2: Recognize associated values
Enums with associated values can store extra data for each case, like a label or number.Final Answer:
To group related values and store extra data in each case -> Option AQuick Check:
Enum with associated values = group + extra data [OK]
- Confusing enums with classes
- Thinking enums only hold fixed values
- Assuming enums are functions
switch in Swift?Solution
Step 1: Recall switch case syntax for enums
In Swift, to match an enum case with associated values, usecase .caseName(let variable):.Step 2: Identify correct pattern
case .someCase(let value): uses the correct dot syntax and binding withlet.Final Answer:
case .someCase(let value): -> Option AQuick Check:
Switch enum case with let binding = case .someCase(let value): [OK]
- Missing dot before case name
- Using = instead of :
- Wrong arrow or braces syntax
enum Direction {
case north, south, east, west
}
let dir = Direction.east
switch dir {
case .north:
print("Going North")
case .south:
print("Going South")
case .east:
print("Going East")
case .west:
print("Going West")
}Solution
Step 1: Identify enum value assigned
The variablediris assignedDirection.east.Step 2: Match switch case
The switch matches.eastcase and prints "Going East".Final Answer:
Going East -> Option DQuick Check:
dir = east prints "Going East" [OK]
- Confusing enum case names
- Forgetting to include all cases
- Assuming default case runs
enum Result {
case success(Int)
case failure(String)
}
let res = Result.success(10)
switch res {
case .success(let value):
print("Value: \(value)")
case failure(let message):
print("Error: \(message)")
}Solution
Step 1: Check switch case syntax
In switch, enum cases must be prefixed with a dot, like.failure.Step 2: Identify missing dot
The second case usesfailurewithout a dot, causing a syntax error.Final Answer:
Missing dot before 'failure' in switch case -> Option CQuick Check:
Enum case in switch needs dot prefix [OK]
- Omitting dot before enum case in switch
- Confusing associated value types
- Forgetting to handle all cases
describeShape(.rectangle(width: 5, height: 10)) print?enum Shape {
case circle(radius: Double)
case rectangle(width: Double, height: Double)
case point
}
func describeShape(_ shape: Shape) {
switch shape {
case .circle(let r):
print("Circle with radius \(r)")
case .rectangle(let w, let h):
print("Rectangle \(w) x \(h)")
case .point:
print("Just a point")
}
}Solution
Step 1: Identify enum case and associated values
The input is.rectangle(width: 5, height: 10), so width = 5 and height = 10.Step 2: Match switch case and print
The switch matches.rectangle(let w, let h)and prints "Rectangle 5.0 x 10.0".Final Answer:
Rectangle 5.0 x 10.0 -> Option BQuick Check:
Rectangle case prints dimensions [OK]
- Using wrong variable names in case
- Missing multiple associated values in pattern
- Assuming default case runs
Ready to prove it?
Pass the test and this pattern moves unknown
