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.
The @ObservableState macro enables SwiftUI views to observe state changes efficiently:
Feature.swift
@Reducerstruct Feature { @ObservableState struct State { var username: String = "" var isLoggedIn: Bool = false } enum Action { case usernameChanged(String) case loginButtonTapped } var body: some Reducer<State, Action> { Reduce { state, action in switch action { case let .usernameChanged(username): state.username = username return .none case .loginButtonTapped: state.isLoggedIn = true return .none } } }}
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).
_$id: ObservableStateID - A unique identifier that changes when state mutates
_$willModify() - Called before any property modification
Observation registrar for tracking access and mutations
// Simplified macro expansion@ObservableStatestruct State { var count: Int = 0 // Generated by macro: var _$id = ObservableStateID() var _$observationRegistrar = ObservationRegistrar() mutating func _$willModify() { _$id._$willModify() }}
@ObservableStateenum LoadingState<Data> { case idle case loading case loaded(Data) case failed(Error)}@ObservableStatestruct State { var data: LoadingState<[Item]> = .idle}