Documentation Index
Fetch the complete documentation index at: https://mintlify.com/pointfreeco/swift-composable-architecture/llms.txt
Use this file to discover all available pages before exploring further.
State Management
The Composable Architecture uses value types (structs and enums) to model application state in a predictable and testable way. State is immutable from the outside and can only be modified by reducers in response to actions.Value Types for State
TCA encourages using Swift structs and enums to define your feature’s state:State.swift
Benefits of Value Types
Predictability
State changes are explicit and traceable through actions
Testability
Easy to construct any state for testing scenarios
Thread Safety
Value semantics eliminate shared mutable state issues
Time Travel
Snapshots enable undo/redo and debugging features
Observable State
The@ObservableState macro enables SwiftUI views to observe state changes efficiently:
Feature.swift
The
@ObservableState macro conforms your state to the ObservableState protocol, which enables observation through Swift’s Observation framework (iOS 17+) or the Perception package (iOS 13-16).How Observable State Works
The macro adds the following to your state type:_$id: ObservableStateID- A unique identifier that changes when state mutates_$willModify()- Called before any property modification- Observation registrar for tracking access and mutations
State Composition
Compose larger state from smaller pieces:AppState.swift
Optional State
Use optionals to represent state that may not exist:Collection State
Manage collections of child features:State Mutations
Correct: Mutate in Reducer
Incorrect: Direct Mutation
Accessing State
Access state from the store in different contexts:In SwiftUI Views
Using withState
For non-observable contexts or when you need a snapshot:Enum State
Model exclusive states using enums:Best Practices
Keep State Minimal
Only store the minimum necessary state. Derive computed values in views or using computed properties.
Use Value Types
Prefer structs and enums over classes for state. This ensures copy-on-write semantics and value equality.
Related Topics
- Reducers - Learn how state is modified
- Store - Understand the runtime container for state
- Composition - Compose state from smaller pieces