0
0
Swiftprogramming~5 mins

Raw values for enums in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Raw values for enums
O(n)
Understanding Time Complexity

Let's see how the time it takes to work with enums that have raw values changes as we use more cases.

We want to know how the program's steps grow when looking up enum values by their raw values.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


enum Direction: String {
    case north = "N"
    case south = "S"
    case east = "E"
    case west = "W"
}

let input = "E"
if let direction = Direction(rawValue: input) {
    print("Found direction: \(direction)")
}
    

This code tries to find an enum case from a raw string value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each enum case's raw value to find a match.
  • How many times: Up to once for each enum case until a match is found.
How Execution Grows With Input

As the number of enum cases grows, the program may check more cases to find a match.

Input Size (number of enum cases)Approx. Operations (checks)
4Up to 4 checks
10Up to 10 checks
100Up to 100 checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to find a matching raw value grows linearly with the number of enum cases.

Common Mistake

[X] Wrong: "Looking up an enum by raw value is instant no matter how many cases there are."

[OK] Correct: The program may need to check each case one by one until it finds a match, so more cases mean more checks.

Interview Connect

Understanding how enum raw value lookups scale helps you explain how your code behaves with more data, a useful skill in real projects and interviews.

Self-Check

"What if the enum used integers as raw values instead of strings? How would the time complexity change?"