0Pricing
Swift Academy · Lesson

Modeling State Machines with Enums

Representing app state transitions safely with Swift enums.

Modeling State Machines with Enums is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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 ```

States with Associated Data

```swift enum LoadState { case idle case loading(progress: Double) case loaded(T) case failed(Error) } var state: LoadState<[String]> = .idle state = .loading(progress: 0.5) state = .loaded(["alice","bob"]) ```

Transition Function

```swift func transition(_ state: LoadState, event: AppEvent) -> LoadState { switch (state, event) { case (.idle, .startFetch): return .loading(progress: 0) case (.loading, .progress(let p)): return .loading(progress: p) case (.loading, .success(let d)): return .loaded(d) case (.loading, .error(let e)): return .failed(e) default: return state } } ```

Why Enum State Machines?

Benefits: • Exhaustive switch — the compiler forces handling all states • Illegal combinations are impossible (e.g. `loaded` without data) • State is a value — easy to test, copy, log • UI can switch on state and render accordingly

UI Rendering from State

```swift func render(_ state: LoadState<[User]>) { switch state { case .idle: showEmptyView() case .loading(let p): showProgress(p) case .loaded(let users): showList(users) case .failed(let err): showError(err) } } ```

Player State Machine

```swift enum PlayerState { case stopped case playing(track: String, position: TimeInterval) case paused(track: String, position: TimeInterval) } ``` Only `playing` and `paused` carry a track — `stopped` doesn't, making the model self-documenting.

Preventing Invalid Transitions

```swift extension PlayerState { mutating func play(track: String) { guard case .stopped = self else { return } self = .playing(track: track, position: 0) } mutating func pause() { if case .playing(let t, let p) = self { self = .paused(track: t, position: p) } } } ```

Testing State Machines

```swift func testLight() { var l = TrafficLight.red assert(l.next() == .green) assert(l.next().next() == .yellow) } ``` State machines with pure transition functions are trivially unit-testable — no mocks needed.

Composing State Machines

Large apps often have multiple state machines working together: ```swift struct AppState { var auth: AuthState var data: LoadState<[Article]> var ui: UIState } ``` Compose them in a single root state struct for Flux/Redux-style architectures.

Quick Check

What makes enum state machines compile-safe?

Recap

Key takeaways: • Each case = a state; transitions = functions returning next state • Associated values carry state-specific data • Exhaustive switch = compiler-enforced state handling • Pure transition functions are easy to unit test • Compose multiple state machines in a root state struct Course complete! Next: protocol composition.

Frequently asked questions

Is the “Modeling State Machines with Enums” lesson free?

Yes — the full text of “Modeling State Machines with Enums” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Modeling State Machines with Enums”?

Representing app state transitions safely with Swift enums. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Modeling State Machines with Enums” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Raw Values and CaseIterable
  2. Associated Values for Rich Data
  3. Indirect Enums and Recursive Structures
  4. Modeling State Machines with Enums
← Back to Swift Academy