Enums with Associated Values
Model a fixed set of states — each carrying its own data — and handle them exhaustively with switch.
Swift enums can attach data to each case. This makes them perfect for modeling screen state, API results and navigation destinations.
switch statements over enums must be exhaustive, so the compiler tells you every place to update when you add a case.
1enum LoadState<Value> {
2 case idle
3 case loading
4 case loaded(Value)
5 case failed(Error)
6}
7
8func render(_ state: LoadState<[String]>) -> String {
9 switch state {
10 case .idle, .loading:
11 return "Loading…"
12 case .loaded(let items):
13 return "\(items.count) items"
14 case .failed(let error):
15 return "Error: \(error.localizedDescription)"
16 }
17}Common pitfalls
- Avoid default: in switches over your own enums — you lose the compiler warning when a new case is added.
Still unclear? Ask BeeAI about Enums with Associated Values.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Related topics
Represent a value that may be missing, and unwrap it safely with if let, guard let and ??.
Throw and catch errors, convert with try? and use Swift 6 typed throws for precise error types.
Data-driven, type-safe navigation that supports deep links and programmatic push/pop.
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans