Raw values for enums in Swift - Time & Space 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.
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 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.
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) |
|---|---|
| 4 | Up to 4 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of enum cases.
Time Complexity: O(n)
This means the time to find a matching raw value grows linearly with the number of enum cases.
[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.
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.
"What if the enum used integers as raw values instead of strings? How would the time complexity change?"