Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .cursor-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
},
"metadata": {
"description": "Professional Cursor plugins with APEX workflow, SOLID principles, and expert development agents for Next.js, Laravel, Swift, Tailwind CSS, and more",
"version": "0.1.18"
"version": "0.1.19"
},
"plugins": [
{
Expand Down Expand Up @@ -535,7 +535,7 @@
"name": "fuse-swift-apple-expert",
"source": ".cursor-plugin/plugins/fuse-swift-apple-expert",
"description": "Expert Swift 6.4.2 + SwiftUI (Xcode 27.2) for iOS 27.2, macOS 27.2, iPadOS 27.2, watchOS 27.2, visionOS 27.2, tvOS 27.2 with Liquid Glass, @Observable, actors, SwiftData inheritance",
"version": "1.1.26",
"version": "1.1.27",
"author": {
"name": "Fusengine",
"email": "hello@fusengine.ch"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fuse-swift-apple-expert",
"version": "1.1.26",
"version": "1.1.27",
"description": "Expert Swift 6.4.2 + SwiftUI (Xcode 27.2) for iOS 27.2, macOS 27.2, iPadOS 27.2, watchOS 27.2, visionOS 27.2, tvOS 27.2 with Liquid Glass, @Observable, actors, SwiftData inheritance",
"author": {
"name": "Fusengine",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ versions:
swift: "6.4.2"
ios: "27.2"
user-invocable: true
references: references/solid-principles.md, references/single-responsibility.md, references/open-closed.md, references/liskov-substitution.md, references/interface-segregation.md, references/dependency-inversion.md, references/concurrency-patterns.md, references/anti-patterns.md, references/templates/view.md, references/templates/viewmodel.md, references/templates/service.md, references/templates/protocol.md, references/templates/model.md
references: references/solid-principles.md, references/single-responsibility.md, references/open-closed.md, references/liskov-substitution.md, references/interface-segregation.md, references/dependency-inversion.md, references/concurrency-patterns.md, references/state-machines.md, references/anti-patterns.md, references/templates/view.md, references/templates/viewmodel.md, references/templates/service.md, references/templates/protocol.md, references/templates/model.md
related-skills: swift-core, swiftui-core, ios, macos, ipados, watchos, visionos, tvos
---

Expand Down Expand Up @@ -81,6 +81,7 @@ File size: the only line limit is the hook ceiling (`FUSE_SOLID_MAX_LINES`). Spl
| **ISP** | [interface-segregation.md](references/interface-segregation.md) | Fat protocols, splitting |
| **DIP** | [dependency-inversion.md](references/dependency-inversion.md) | Injection, testing, mocking |
| **Concurrency** | [concurrency-patterns.md](references/concurrency-patterns.md) | Actors, @MainActor, Sendable |
| **State modeling** | [state-machines.md](references/state-machines.md) | Boolean soup, `LoadState`, transitions |
| **Anti-Patterns** | [anti-patterns.md](references/anti-patterns.md) | Code smells detection |

### Templates
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ actor UserCache {
@MainActor
@Observable
final class UserViewModel {
var user: User?
var isLoading = false
// One state value instead of separate data/loading flags: see state-machines.md
private(set) var state: LoadState<User> = .idle

private let service: UserServiceProtocol

Expand All @@ -56,9 +56,9 @@ final class UserViewModel {
}

func load() async {
isLoading = true
defer { isLoading = false }
user = try? await service.fetchCurrentUser()
state = .loading
do { state = .loaded(try await service.fetchCurrentUser()) }
catch { state = .failed(LoadFailure(error)) }
}
}
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,18 @@ final class UserService: UserServiceProtocol {
// Features/User/ViewModels/UserViewModel.swift
@MainActor @Observable
final class UserViewModel {
var user: User?
var isLoading = false
// `LoadState` is defined in state-machines.md
private(set) var state: LoadState<User> = .idle
private let service: UserServiceProtocol

init(service: UserServiceProtocol) {
self.service = service
}

func load() async {
isLoading = true
defer { isLoading = false }
user = try? await service.fetchCurrentUser()
state = .loading
do { state = .loaded(try await service.fetchCurrentUser()) }
catch { state = .failed(LoadFailure(error)) }
}
}
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,15 @@ Shared code: `Core/Services/`, `Core/Protocols/`, `Core/Extensions/`
```swift
// Features/User/Views/UserView.swift - 200+ lines!
struct UserView: View {
@State private var user: User?
@State private var isLoading = false
@State private var state: LoadState<User> = .idle // see state-machines.md

var body: some View {
VStack { /* 150 lines of UI */ }
.onAppear {
Task {
let url = URL(string: "https://api.example.com/user")!
let (data, _) = try await URLSession.shared.data(from: url)
user = try JSONDecoder().decode(User.self, from: data)
state = .loaded(try JSONDecoder().decode(User.self, from: data))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
---
name: state-machines
applies-to: "**/*.swift"
description: Model state so illegal states are unrepresentable - sum types by default, transition functions when order matters
when-to-use: ViewModel state, loading/error states, multi-step flows, playback, sync, any boolean-flag soup
keywords: state machine, enum, sum type, illegal states, boolean soup, LoadState, Sendable, Equatable, Swift 6
priority: high
related: templates/viewmodel.md, templates/view.md, anti-patterns.md, concurrency-patterns.md
---

# State Modeling for Swift

**Make illegal states unrepresentable. Model mutually-exclusive states as one type, not independent flags.**

State modeling is tiered. Start at Tier 1; escalate to Tier 2 only when transition order matters.

Credit: adapted from the `coreyfloyd/agents` fork (https://github.com/coreyfloyd/agents).

---

## The anti-pattern: boolean soup

Independent flags for mutually-exclusive states let contradictory combinations exist.

```swift
// BAD: three flags = 2^3 = 8 combos, most illegal
@Observable final class FeatureViewModel {
var data: FeatureData?
var isLoading = false
var error: Error?
}
// loading + error + data all set at once? The type permits it. Bugs live here.
```

If two or more properties are **mutually exclusive** (only one should be true at a time), they are not separate properties: they are one state.

---

## Tier 1 - Sum-type modeling (default)

Model the set of valid states as one `enum`. Illegal states become unrepresentable. This is the baseline for almost every ViewModel.

`LoadState` is defined **once**, here. Shared by 2+ features, so it lives in `Core/Models/LoadState.swift`; the ViewModel and View templates reference it, never redefine it.

```swift
// Core/Models/LoadState.swift
import Foundation

/// A `Sendable` and `Equatable` snapshot of a failure.
///
/// A bare `any Error` is neither `Equatable` nor guaranteed `Sendable`, so the
/// failure case carries this value instead of the raw error.
struct LoadFailure: LocalizedError, Sendable, Equatable {
/// Human-readable description, already localized at capture time.
let message: String

init(message: String) { self.message = message }

/// Captures an error as a value.
init(_ error: any Error) { self.message = error.localizedDescription }

/// Keeps `localizedDescription` equal to `message` when the failure is shown as an `Error`.
var errorDescription: String? { message }
}

/// The lifecycle of an asynchronous load: exactly one case at a time.
enum LoadState<Value: Sendable>: Sendable {
case idle
case loading
case loaded(Value)
case failed(LoadFailure)
}

/// `Equatable` whenever the payload is, so state changes can be asserted in tests.
extension LoadState: Equatable where Value: Equatable {}
```

Use it in a ViewModel:

```swift
@MainActor
@Observable
final class FeatureViewModel {
private(set) var state: LoadState<FeatureData> = .idle
private let service: FeatureServiceProtocol

init(service: FeatureServiceProtocol) { self.service = service }

func load() async {
state = .loading
do { state = .loaded(try await service.fetchData()) }
catch { state = .failed(LoadFailure(error)) }
}
}
```

Drive the view with an **exhaustive `switch`**: the compiler forces you to handle every state.

```swift
var body: some View {
switch viewModel.state {
case .idle, .loading: ProgressView()
case .loaded(let data): FeatureContent(data: data)
case .failed(let error): ErrorView(error: error) {
Task { await viewModel.load() }
}
}
}
```

**Tier 1 is enough when** any state can follow any other and you only need to represent the current one (most load/error screens, simple toggles).

---

## Tier 2 - State machine (when transition order matters)

Escalate when only certain transitions are legal and an illegal jump is a bug: playback, multi-step wizards, onboarding, sync, connection lifecycle. Add **events** and a **transition function** that rejects illegal moves. Name the types after the flow (`ItemsFlowState`, not a generic `State`).

```swift
enum ItemsFlowState: Equatable, Sendable {
case idle, loading, loaded([Item]), failed(LoadFailure)
}
enum ItemsFlowEvent: Equatable, Sendable {
case load, succeeded([Item]), failed(LoadFailure), reset
}

extension ItemsFlowState {
/// Returns the next state, or nil if the transition is illegal.
func applying(_ event: ItemsFlowEvent) -> ItemsFlowState? {
switch (self, event) {
case (.idle, .load), (.failed, .load): return .loading
case (.loading, .succeeded(let items)): return .loaded(items)
case (.loading, .failed(let failure)): return .failed(failure)
case (_, .reset): return .idle
default: return nil // illegal: rejected
}
}
}

@MainActor
@Observable
final class ItemsFlowViewModel {
private(set) var state: ItemsFlowState = .idle

/// Single funnel for all state changes; illegal transitions are dropped (or asserted).
func send(_ event: ItemsFlowEvent) {
guard let next = state.applying(event) else {
assertionFailure("Illegal transition: \(event) from \(state)")
return
}
state = next
}
}
```

`Item` is your own `Sendable & Equatable` model (see `templates/model.md`).

Key properties of Tier 2:
- **One funnel** (`send`): state is never mutated directly from scattered call sites.
- **Illegal transitions are rejected at runtime**, not just illegal states unrepresentable.
- The transition table is the spec: reviewers read legality in one place.

---

## When to use which

| Situation | Tier |
|-----------|------|
| Load/error/empty screen, any order valid | **1** - sum type |
| A flag pair that's mutually exclusive | **1** - collapse into an enum |
| Audio/video playback, sync, connection lifecycle | **2** - transitions matter |
| Multi-step wizard / onboarding where back/skip rules exist | **2** |
| Order/job lifecycle with forbidden jumps | **2** |

Default to Tier 1. Reach for Tier 2 when you can name a transition that must not happen.

---

## Checklist

- [ ] No set of mutually-exclusive `Bool`/optional properties on one type (boolean soup)
- [ ] Mutually-exclusive states modeled as one `enum` (Tier 1)
- [ ] Failure payloads are `Sendable` + `Equatable` (`LoadFailure`), never a bare `any Error`
- [ ] Views driven by an exhaustive `switch` over the state, no `if isLoading ... else if error ...`
- [ ] If transition order matters: a single `send`/transition funnel rejecting illegal moves (Tier 2)
- [ ] State is `private(set)`: mutated only through the ViewModel's own methods
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,14 @@ struct FeatureView: View {

var body: some View {
Group {
if viewModel.isLoading {
// Exhaustive switch over one state value: the compiler enforces every case.
// `LoadState` is defined in references/state-machines.md.
switch viewModel.state {
case .idle, .loading:
ProgressView()
} else if let data = viewModel.data {
case .loaded(let data):
FeatureContent(data: data)
} else if let error = viewModel.error {
case .failed(let error):
ErrorView(error: error) {
Task { await viewModel.load() }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ import Foundation
@Observable
final class FeatureViewModel {
// MARK: - State
// Mutually-exclusive states as ONE value: illegal states are unrepresentable.
// `LoadState<Value>` / `LoadFailure` are defined once in
// references/state-machines.md (Core/Models/LoadState.swift).

var data: FeatureData?
var isLoading = false
var error: Error?
private(set) var state: LoadState<FeatureData> = .idle

// MARK: - Dependencies

Expand All @@ -48,24 +49,18 @@ final class FeatureViewModel {

/// Loads feature data from API.
func load() async {
isLoading = true
defer { isLoading = false }

do {
data = try await service.fetchData()
error = nil
} catch {
self.error = error
}
state = .loading
do { state = .loaded(try await service.fetchData()) }
catch { state = .failed(LoadFailure(error)) }
}

/// Refreshes data (pull-to-refresh).
/// Refreshes data (pull-to-refresh) without flashing the loading state.
/// A failed refresh keeps the content already on screen.
func refresh() async {
do {
data = try await service.fetchData()
error = nil
} catch {
self.error = error
do { state = .loaded(try await service.fetchData()) }
catch {
if case .loaded = state { return }
state = .failed(LoadFailure(error))
}
}
}
Expand All @@ -75,13 +70,13 @@ final class FeatureViewModel {
extension FeatureViewModel {
static var preview: FeatureViewModel {
let vm = FeatureViewModel(service: MockFeatureService())
vm.data = .preview
vm.state = .loaded(.preview) // private(set) is settable in-file
return vm
}

static var previewLoading: FeatureViewModel {
let vm = FeatureViewModel(service: MockFeatureService())
vm.isLoading = true
vm.state = .loading
return vm
}
}
Expand Down
Loading
Loading