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?"
Practice
Solution
Step 1: Understand what raw values are
Raw values are fixed values assigned to enum cases, like strings or numbers.Step 2: Identify the purpose of raw values
They help convert enum cases to simple data types for saving or displaying.Final Answer:
To assign fixed simple values like strings or numbers to enum cases -> Option BQuick Check:
Raw values = fixed simple values [OK]
- Thinking raw values make enums mutable
- Confusing raw values with associated values
- Believing enums can inherit from classes
Solution
Step 1: Check enum declaration with raw values
Raw values require specifying the type after enum name, e.g., : String.Step 2: Verify correct case syntax
Cases use 'case name = value' syntax, separated by new lines or semicolons.Final Answer:
enum Direction: String { case north = "N" case south = "S" } -> Option CQuick Check:
Raw value enum syntax = enum Direction: String { case north = "N" case south = "S" } [OK]
- Omitting the raw value type after enum name
- Using commas instead of separate case lines
- Assigning raw values without specifying type
enum Weekday: Int {
case monday = 1
case tuesday
case wednesday
}
print(Weekday.tuesday.rawValue)Solution
Step 1: Understand raw value auto-increment
When the first case has a raw value (1), following cases auto-increment by 1.Step 2: Identify raw value of 'tuesday'
Since monday = 1, tuesday = 2, wednesday = 3.Final Answer:
2 -> Option DQuick Check:
Auto-increment raw values = 2 [OK]
- Assuming all raw values must be explicitly assigned
- Confusing rawValue with case index
- Expecting an error when accessing rawValue
enum Color: String {
case red = 1
case green = "Green"
case blue = "Blue"
}Solution
Step 1: Check raw value type consistency
The enum declares raw type String, so all raw values must be strings.Step 2: Identify the incorrect raw value
Case 'red' has raw value 1 (an Int), which conflicts with String type.Final Answer:
Raw values must all be of the declared type String -> Option AQuick Check:
Raw values must match enum type [OK]
- Mixing raw value types in one enum
- Thinking semicolons are required after cases
- Believing enums can't have raw values
enum StatusCode: Int {
case success = 200
case notFound = 404
case serverError = 500
}
func message(for code: Int) -> String {
if let status = StatusCode(rawValue: code) {
switch status {
case .success: return "OK"
case .notFound: return "Not Found"
case .serverError: return "Server Error"
}
} else {
return "Unknown"
}
}
print(message(for: 404))
print(message(for: 201))
What is the output?Solution
Step 1: Understand rawValue initializer
StatusCode(rawValue: 404) returns .notFound; 201 returns nil.Step 2: Trace function output for each input
For 404, returns "Not Found"; for 201, returns "Unknown".Final Answer:
Not Found Unknown -> Option AQuick Check:
Raw value init maps code to enum or nil [OK]
- Assuming rawValue init always returns a case
- Confusing rawValue with case index
- Expecting runtime error for unknown raw value
Ready to prove it?
Pass the test and this pattern moves unknown
