Associated values per case in Swift - Time & Space Complexity
We want to understand how the time it takes to work with enums that have associated values changes as we use more cases or values.
How does the program's work grow when we handle different enum cases with associated data?
Analyze the time complexity of the following code snippet.
enum Device {
case phone(model: String)
case tablet(model: String)
case laptop(model: String)
}
func printDevice(_ device: Device) {
switch device {
case .phone(let model):
print("Phone model: \(model)")
case .tablet(let model):
print("Tablet model: \(model)")
case .laptop(let model):
print("Laptop model: \(model)")
}
}
This code defines an enum with associated values and a function that matches each case to print its model.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement checks the enum case once per call.
- How many times: Exactly once for each enum value processed.
Each time we call the function with a device, it does one check to find the matching case.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of enum values processed, one check per value.
Time Complexity: O(n)
This means the time to process devices grows in a straight line with how many devices you handle.
[X] Wrong: "Matching enum cases with associated values takes longer for each case because of the extra data."
[OK] Correct: The switch checks the case once per value, and the associated data is accessed directly without extra loops, so the time per value stays constant.
Understanding how enum case matching scales helps you explain how your code handles different data efficiently and clearly.
"What if we added a loop inside each case to process the model string character by character? How would the time complexity change?"
Practice
Solution
Step 1: Understand enum cases
Enum cases represent fixed options, but sometimes need extra data.Step 2: Role of associated values
Associated values let each case carry extra information, like a label or number.Final Answer:
To store extra data with each enum case -> Option AQuick Check:
Associated values = extra data per case [OK]
- Confusing associated values with raw values
- Thinking enums can inherit properties
- Believing enums can contain functions only
Solution
Step 1: Recall enum case syntax with associated values
Associated values use parentheses after the case name with the type inside.Step 2: Match syntax options
Only 'case name(String)' uses parentheses correctly for associated values.Final Answer:
case name(String) -> Option BQuick Check:
Parentheses hold associated value type [OK]
- Using colon instead of parentheses
- Using equals sign for associated values
- Using arrow notation incorrectly
enum Result {
case success(String)
case failure(Int)
}
let response = Result.success("Done")
switch response {
case .success(let message):
print(message)
case .failure(let code):
print("Error code: \(code)")
}Solution
Step 1: Identify enum case used
The variable 'response' is assigned 'Result.success("Done")'.Step 2: Switch matches .success case
The switch matches '.success(let message)' and prints the message string.Final Answer:
Done -> Option DQuick Check:
Matching case prints associated string [OK]
- Confusing success and failure cases
- Expecting error code instead of message
- Thinking code will not compile
enum Device {
case phone(model: String)
case tablet(model: String)
}
let myDevice = Device.phone("iPhone")Solution
Step 1: Check enum case declaration
Cases use labeled associated values: 'phone(model: String)'.Step 2: Check enum instance assignment
Assigning 'Device.phone("iPhone")' omits the label 'model:'.Final Answer:
Cannot assign associated value without label -> Option CQuick Check:
Labeled associated values require labels on assignment [OK]
- Ignoring labels in associated values
- Thinking parentheses are missing
- Believing enums can't have associated values
enum Message {
case text(String, Int)
case image(url: String, size: (width: Int, height: Int))
}
let msg = Message.image(url: "photo.png", size: (width: 100, height: 200))
switch msg {
case .text(let content, let length):
print("Text: \(content), length: \(length)")
case .image(let url, let size):
print("Image URL: \(url), size: \(size.width)x\(size.height)")
}What will be printed?Solution
Step 1: Identify enum case and associated values
Variable 'msg' is assigned '.image' with url and size tuple.Step 2: Switch matches .image case and prints values
Print statement accesses url and tuple's width and height correctly.Final Answer:
Image URL: photo.png, size: 100x200 -> Option AQuick Check:
Tuple values accessed with dot notation [OK]
- Printing tuple as whole instead of parts
- Confusing .text and .image cases
- Expecting compilation error from tuple
Ready to prove it?
Pass the test and this pattern moves unknown
