0
0
Swiftprogramming~5 mins

Switch with where clauses in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch with where clauses
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a switch statement with where clauses changes as the input grows.

Specifically, how many checks does the program do when matching cases with conditions?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let numbers = [1, 2, 3, 4, 5]

for number in numbers {
    switch number {
    case let x where x % 2 == 0:
        print("Even number: \(x)")
    case let x where x % 2 != 0:
        print("Odd number: \(x)")
    default:
        print("Unknown")
    }
}
    

This code goes through a list of numbers and uses a switch with where clauses to check if each number is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each number in the array.
  • How many times: Once for each number in the list (n times).
  • Inside the loop, the switch checks conditions, but these are a fixed small number of checks per item.
How Execution Grows With Input

As the list gets bigger, the program checks each number once with a few conditions.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The number of checks grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items to check.

Common Mistake

[X] Wrong: "The where clauses make the switch run slower for each item because they add extra loops."

[OK] Correct: Each where clause is just a simple condition checked once per item, not a loop. So it doesn't multiply the work by more than a small constant.

Interview Connect

Understanding how switch statements with conditions scale helps you explain your code's efficiency clearly and confidently.

Self-Check

"What if we added a nested loop inside the switch cases? How would the time complexity change?"