Coding/Learn/swift/swift enums and associated values
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnEnums, Raw Values & Associated Values (Tagged Unions)
12 / 20 0%
Lesson 12 of 20
10 mins read

Enums, Raw Values & Associated Values (Tagged Unions)

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Algebraic Data Types: Associated values enable precise state modeling (e.g. Loading, Success(Data), Error(Error)).
Point star
CaseIterable Protocol: Conforming to CaseIterable automatically synthesizes an .allCases collection.
Point star
Dot Syntax: Swift infers enum types from context: let dir: Direction = .north.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use indirect enum for recursive data structures like linked lists or binary trees.

Live Interactive Example

Hit Run Code to see it live
Network State Machine with Associated Values
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Output Console
Click "Run Code" to view the rendered output.
How it works: switch unwrapped the exact associated value payloads for each network state.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Payment Method Enum with Associated Values

  • PointDefine an enum PaymentMethod with cases .creditCard(last4: String) and .cash(amount: Double).
  • PointWrite a function describePayment(_ method: PaymentMethod) -> String using a switch statement.
  • PointFor creditCard, return "Card ending in \(last4)". For cash, return "Cash payment of $\(amount)".
  • PointIn top-level code, call and print describePayment(.creditCard(last4: "4242")).
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates