Modeling State Machines with Enums
Representing app state transitions safely with Swift enums.
Welcome
Enums are ideal for modelling finite state machines. Each case is a state; transitions are functions that return the next state. This approach makes illegal states unrepresentable.
Simple State Enum
```swift
enum TrafficLight {
case red, yellow, green
func next() -> TrafficLight {
switch self {
case .red: return .green
case .green: return .yellow
case .yellow: return .red
}
}
}
var light = TrafficLight.red
light = light.next() // .green
```
All lessons in this course
- Raw Values and CaseIterable
- Associated Values for Rich Data
- Indirect Enums and Recursive Structures
- Modeling State Machines with Enums