0
0
Swiftprogramming~5 mins

Switch must be exhaustive in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch must be exhaustive
O(1)
Understanding Time Complexity

We want to see how the time it takes to run a switch statement changes as the number of cases grows.

How does adding more cases affect the work the program does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


enum Direction {
    case north, south, east, west
}

func move(_ direction: Direction) {
    switch direction {
    case .north:
        print("Moving north")
    case .south:
        print("Moving south")
    case .east:
        print("Moving east")
    case .west:
        print("Moving west")
    }
}

This code uses a switch to handle all possible directions in an enum. The switch is exhaustive, covering every case, allowing compiler optimizations.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch statement dispatches directly to the matching case.
  • How many times: Constant time (1 operation), no repetition regardless of cases.
How Execution Grows With Input

Swift compiler optimizes exhaustive switches on enums using jump tables or direct indexing, making execution constant time.

Input Size (number of cases)Approx. Operations
41 operation
101 operation
1001 operation

Pattern observation: Operations remain constant, independent of cases.

Final Time Complexity

Time Complexity: O(1)

The time is constant due to compiler optimizations like jump tables for exhaustive enums.

Common Mistake

[X] Wrong: "Switch statements check cases sequentially, so O(n)."

[OK] Correct: Compilers generate efficient code (jump tables, hash tables), not linear scans. Exhaustive switches enable perfect optimization.

Interview Connect

Knowing switch optimizations demonstrates understanding of compiler behavior and efficient code generation.

Self-Check

"What if the switch used a default case instead of listing all cases? How would that affect the time complexity?"