Enums with associated values let you store extra information with each option. This helps keep related data together in a simple way.
Enums with associated values in iOS Swift
enum Example {
case optionName(AssociatedType)
}Each case can have one or more associated values inside parentheses.
Associated values can be any type, like String, Int, or even custom types.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}enum Result {
case success(String)
case failure(Error)
}This example defines a Media enum with two cases holding different data. The describe function uses a switch to read the associated values and return a description string.
enum Media {
case photo(name: String, sizeMB: Double)
case video(name: String, durationSec: Int)
}
func describe(media: Media) -> String {
switch media {
case .photo(let name, let sizeMB):
return "Photo named \"\(name)\" with size \(sizeMB)MB"
case .video(let name, let durationSec):
return "Video named \"\(name)\" lasting \(durationSec) seconds"
}
}
let myPhoto = Media.photo(name: "Beach", sizeMB: 3.5)
let myVideo = Media.video(name: "Birthday", durationSec: 120)
print(describe(media: myPhoto))
print(describe(media: myVideo))You can use named parameters in associated values for clarity.
Switch statements must cover all enum cases, so you handle every possibility.
Associated values let you keep related data together without extra classes or structs.
Enums with associated values store extra data with each case.
Use switch to access and use the associated values.
This helps organize related options and their data cleanly.
Practice
enum with associated values in Swift?Solution
Step 1: Understand enum basics
An enum groups related values under one type.Step 2: Recognize associated values role
Associated values let each case hold extra data, like a number or string.Final Answer:
To store extra data along with each enum case -> Option AQuick Check:
Enums with associated values store extra data [OK]
- Confusing enums with classes
- Thinking enums only hold fixed values
- Mixing associated values with raw values
Solution
Step 1: Recall enum case syntax with associated values
Use parentheses after the case name to specify the type of associated value.Step 2: Match correct syntax
Onlycase name(String)uses parentheses correctly.Final Answer:
case name(String) -> Option BQuick Check:
Use parentheses for associated value types [OK]
- Using colon instead of parentheses
- Assigning value with equals sign
- Using arrow notation
enum Result {
case success(String)
case failure(Int)
}
let result = Result.success("Done")
switch result {
case .success(let message):
print(message)
case .failure(let code):
print("Error \(code)")
}Solution
Step 1: Identify enum case used
The variableresultis.success("Done").Step 2: Follow switch matching
The switch matches.success(let message)and prints the message "Done".Final Answer:
Done -> Option CQuick Check:
Matching case prints associated string [OK]
- Printing the enum case name instead of value
- Confusing success and failure cases
- Not using let to extract associated value
enum Direction {
case up(Int)
case down(Int)
}
let dir = Direction.up(10)
switch dir {
case .up:
print("Going up")
case .down:
print("Going down")
}Solution
Step 1: Check enum cases with associated values
Casesupanddownhave Int associated values.Step 2: Analyze switch cases
Switch cases.upand.downdo not extract the Int value withlet, causing a compile error.Final Answer:
Switch cases must extract associated values with let -> Option AQuick Check:
Extract associated values in switch cases [OK]
- Ignoring associated values in switch
- Thinking default case is mandatory
- Wrong enum initialization
success carrying a String message, failure carrying an Int error code, and loading with no data. Which is the correct enum definition?Solution
Step 1: Match each case with correct associated value
successneeds a String,failurean Int,loadingno data.Step 2: Check each option
enum NetworkResponse { case success(String) case failure(Int) case loading } matches exactly: success(String), failure(Int), loading without value.Final Answer:
enum NetworkResponse { case success(String) case failure(Int) case loading } -> Option DQuick Check:
Define cases with correct associated types [OK]
- Adding wrong types to cases
- Combining multiple values in one case incorrectly
- Assigning associated values to cases that should have none
Ready to prove it?
Pass the test and this pattern moves unknown
