Associated Values in Swift

From the Swift cheat sheet · Enums · verified Jul 2026

Associated Values

Enums with different value types

swift
// Associated values
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")

// Pattern matching with associated values
switch productBarcode {
case .upc(let system, let manufacturer, let product, let check):
    print("UPC: \(system), \(manufacturer), \(product), \(check)")
case .qrCode(let code):
    print("QR code: \(code)")
}
💡 Associated values can be different types for each case
⚡ Use where clauses for additional pattern matching
📌 indirect enables recursive enum definitions
🟢 Associated values are extracted with let/var binding

More Swift tasks

Back to the full Swift cheat sheet