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.
Syntax
enum EnumName {
case caseName(label: Type)
case other(Type, Type)
}
let value = EnumName.caseName(label: data)
switch value {
case .caseName(let label): /* use label */
case .other(let a, let b): /* use a, b */
}
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
// Define an enum `NetworkResult` listing its possible cases
enum NetworkResult {
// Case `success`
case success(code: Int)
// Case `failure`
case failure(message: String)
}
// Declare a constant `result`, set to `NetworkResult.success(code: 200)`
let result = NetworkResult.success(code: 200)
// Switch on `result` and branch by case
switch result {
// Case: `.success(let code)`
case .success(let code):
// Print "Success with code \(code)" to the console
print("Success with code \(code)")
// Case: `.failure(let message)`
case .failure(let message):
// Print "Failed: \(message)" to the console
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
// Define an enum `Shape` listing its possible cases
enum Shape {
// Case `circle`
case circle(radius: Double)
// Enum case(s): `rectangle(width: Double, height: Double)`
case rectangle(width: Double, height: Double)
}
// Declare a constant `shapes`, set to `[Shape.circle(radius: 3), Shape.rectangle(width: 4, height: 5)]`
let shapes = [Shape.circle(radius: 3), Shape.rectangle(width: 4, height: 5)]
// Loop over `shapes`, binding each item to `shape`
for shape in shapes {
// Switch on `shape` and branch by case
switch shape {
// Case: `.circle(let radius)`
case .circle(let radius):
// Print "Circle with radius \(radius)" to the console
print("Circle with radius \(radius)")
// Case: `.rectangle(let width, let height)`
case .rectangle(let width, let height):
// Print "Rectangle \(width) x \(height)" to the console
print("Rectangle \(width) x \(height)")
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: