Swift Tutorial · Collections and Types · Lesson 15 of 30
Swift Enums
Enums with raw values, associated values, methods, CaseIterable, and exhaustive switch.
Raw values and CaseIterable
Enum cases can have raw values (strings or numbers) and conform to CaseIterable to list every case.
enum Plan: String, CaseIterable {
case free, pro, team
var monthlyPrice: Double {
switch self {
case .free: 0
case .pro: 10.11
case .team: 25
}
}
}
for plan in Plan.allCases { print(plan.rawValue, plan.monthlyPrice) }
print(Plan(rawValue: "pro") as Any)
print(Plan(rawValue: "gold") as Any)
Output
free 0.0 pro 10.11 team 25.0 Optional(main.Plan.pro) nil
Run this on your computer — see “Get Started” for setup.
Associated values
Each case can carry different data. A switch must handle every case, so adding a case shows you every place
to update. This is how Swift models results and UI state.
enum LoadState {
case loading
case loaded([String])
case failed(message: String)
}
func render(_ state: LoadState) -> String {
switch state {
case .loading: "Spinner"
case .loaded(let items) where items.isEmpty: "Nothing here yet"
case .loaded(let items): "List of \(items.count) items"
case .failed(let message): "Error: \(message)"
}
}
for state in [LoadState.loading, .loaded([]), .loaded(["a", "b"]), .failed(message: "offline")] {
print(render(state))
}
Output
Spinner Nothing here yet List of 2 items Error: offline
Run this on your computer — see “Get Started” for setup.
Test yourself
What makes Swift enums good for modelling states like loading/loaded/failed?
They are classesCases can carry associated values and switch must be exhaustiveThey can be nilThey are always strings
Show answer
Answer: Cases can carry associated values and switch must be exhaustive