Associated Values
An associated value is extra custom information you can attach to just one specific choice of an enum, like a barcode number attached only to the "scanned item" option.
Declaring Associated Values
A case can declare one or more associated values in parentheses, letting each instance of that case carry its own custom data.
Example: Declaring Associated Values
enum NetworkResult {
case success(code: Int)
case failure(message: String)
}
let result = NetworkResult.success(code: 200)
switch result {
case .success(let code):
print("Success with code \(code)")
case .failure(let message):
print("Failed: \(message)")
}
Login to try C/C++/Java/PHP code in the editor
Different Cases Carrying Different Data
Each case in an enum can carry a completely different shape of associated data, tailored to what that specific case represents.
Example: Different Cases Carrying Different Data
enum Shape {
case circle(radius: Double)
case rectangle(width: Double, height: Double)
}
let shapes = [Shape.circle(radius: 3), Shape.rectangle(width: 4, height: 5)]
for shape in shapes {
switch shape {
case .circle(let radius):
print("Circle with radius \(radius)")
case .rectangle(let width, let height):
print("Rectangle \(width) x \(height)")
}
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing associated values (data attached per-instance, extracted via pattern matching) with raw values (a single fixed value per case, retrieved via
.rawValue). - Forgetting you must use
switchorif casewithlet/varbindings to extract associated values -- you can't access them like a normal property. - Trying to give an enum both raw values and associated values on the same cases; Swift doesn't allow mixing the two on one enum.
Chapter Summary
- Associated values let each case carry its own extra data of specified types.
- Extracting associated values requires pattern matching, typically with
switchorif case. - Different cases in the same enum can carry entirely different associated data.
- Associated values make enums powerful for modeling variant data, like network results.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: