0
0
Swiftprogramming~5 mins

Iterating enum cases with CaseIterable in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iterating enum cases with CaseIterable
O(n)
Understanding Time Complexity

When we loop through all cases of an enum using CaseIterable, we want to know how the time needed grows as the number of cases increases.

We ask: How does the work change if the enum has more or fewer cases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

for direction in Direction.allCases {
    print(direction)
}

This code loops through all possible directions defined in the enum and prints each one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each enum case in Direction.allCases.
  • How many times: Once for each case in the enum.
How Execution Grows With Input

As the number of enum cases grows, the loop runs once for each case.

Input Size (n)Approx. Operations
44 (one print per case)
1010
100100

Pattern observation: The work grows directly with the number of enum cases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows in a straight line as the number of enum cases increases.

Common Mistake

[X] Wrong: "Looping over enum cases is constant time because enums are fixed."

[OK] Correct: Even though enums have fixed cases, the loop still runs once per case, so time grows with the number of cases.

Interview Connect

Understanding how looping over enum cases scales helps you explain your code's efficiency clearly and confidently in real-world coding discussions.

Self-Check

What if we nested another loop inside to print each case twice? How would the time complexity change?