← Back to Swift Course | Chapter 10: Enums | Lesson 3 of 6

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

markup
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)")
}

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

markup
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)")
    }
}
Common Mistakes
  1. Confusing associated values (data attached per-instance, extracted via pattern matching) with raw values (a single fixed value per case, retrieved via .rawValue).
  2. Forgetting you must use switch or if case with let/var bindings to extract associated values -- you can't access them like a normal property.
  3. 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 switch or if 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.