Python Enums, Raw Values & Associated Values (Tagged Unions)
Swift Enums are first-class types that surpass traditional C/Java enums. Learn basic enums, Raw Values (String, Int), CaseIterable, and Associated Values for modeling rich domain states and algebraic data types.
"A raw enum is like a menu with numbered items (Option 1, Option 2). An enum with associated values is like an order receipt that holds custom toppings: case pizza(size: "Large", toppings: ["Cheese", "Mushrooms"])."
Deep Dive: How It Works
First-Class Types: Enums can have methods, computed properties, and initializers.
Raw Values: enum Direction: String { case north = "N", south = "S" } allows .rawValue access.
Associated Values: Store custom heterogeneous data alongside each case (e.g. case qrCode(String), case barcode(Int, Int)).
Pattern Matching: Use switch or if case let to extract associated values safely.
Syntax Blueprint
enum Result {
case success(data: String)
case failure(code: Int, error: String)
}
switch res {
case .success(let data): print(data)
case .failure(let code, let err): print("\(code): \(err)")
}Declare associated value payloads and unwrap them using pattern matching in switch cases.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to give an enum both raw values and associated values at the same time.Why it happens: Swift enums are either raw-value enums OR associated-value enums, never both.
How to fix: Use associated values if dynamic payloads need to be attached to cases.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Payment Method Enum with Associated Values
Define an enum PaymentMethod with cases .creditCard(last4: String) and .cash(amount: Double).
Write a function describePayment(_ method: PaymentMethod) -> String using a switch statement.
For creditCard, return "Card ending in \(last4)". For cash, return "Cash payment of $\(amount)".
In top-level code, call and print describePayment(.creditCard(last4: "4242")).
Finished reading and practicing?
Mark this lesson as completed to update your course progress.