Skip to content

Quick Start

ChiefVenzox edited this page Jun 5, 2026 · 1 revision

Quick Start

This guide builds a small counter with SwiftState.

1. Define State

import SwiftState

struct AppState: State {
    var counter: Int = 0
}

State requires Codable, Equatable, and Sendable. This keeps state serializable, comparable, and safe for Swift concurrency boundaries.

2. Define Actions

enum AppAction: Action {
    case increment
    case decrement
}

Actions describe user intent or system events. Views dispatch actions; reducers decide how state changes.

3. Create A Reducer

let appReducer: Reducer<AppState> = { state, action in
    guard let action = action as? AppAction else { return }
    switch action {
    case .increment:
        state.counter += 1
    case .decrement:
        state.counter -= 1
    }
}

Reducers are synchronous and predictable. They mutate the inout state for the action they understand.

4. Create The Store

@StateObject private var store = Store(
    initialState: AppState(),
    reducer: appReducer
)

Create the store once near your app entry point.

5. Use It In SwiftUI

struct ContentView: View {
    @EnvironmentObject var store: Store<AppState>

    var body: some View {
        VStack(spacing: 16) {
            Text("Count: \(store.state.counter)")

            Button("Increment") {
                store.dispatch(AppAction.increment)
            }

            Button("Decrement") {
                store.dispatch(AppAction.decrement)
            }
        }
    }
}

Inject the store:

ContentView()
    .environmentObject(store)

Next Steps

Clone this wiki locally