Type-safe async state machine with built-in logging and SwiftUI bindings
.package(url: "https://github.com/philiprehberger/swift-state-kit.git", from: "0.1.0")Type-safe async state machine with built-in logging and SwiftUI bindings
Add to your Package.swift:
dependencies: [
.package(url: "https://github.com/philiprehberger/swift-state-kit.git", from: "0.1.0")
]
Then add "StateKit" to your target dependencies:
.target(name: "YourTarget", dependencies: [
.product(name: "StateKit", package: "swift-state-kit")
])
import StateKit
// Define states and events
enum OrderState: Hashable, Sendable {
case pending, confirmed, shipped, delivered
}
enum OrderEvent: Hashable, Sendable {
case confirm, ship, deliver
}
// Define transitions
let machine = StateMachine(
initial: OrderState.pending,
transitions: [
Transition(from: .pending, on: .confirm, to: .confirmed),
Transition(from: .confirmed, on: .ship, to: .shipped),
Transition(from: .shipped, on: .deliver, to: .delivered)
]
)
let state = try await machine.send(.confirm) // => .confirmed
Transition(from: .pending, on: .confirm, to: .confirmed) {
try await sendConfirmationEmail()
}
let machine = StateMachine(
initial: OrderState.pending,
transitions: transitions,
logger: .console
)
// Logs: "[StateKit] pending --confirm--> confirmed"
struct OrderView: View {
@State private var machine = ObservableStateMachine(machine: orderMachine)
var body: some View {
VStack {
Text("Status: \(machine.state)")
Button("Confirm") { Task { try await machine.send(.confirm) } }
.disabled(!await machine.canSend(.confirm))
}
}
}
| Method | Description |
|---|---|
init(initial:transitions:logger:) | Create a state machine with initial state and transitions |
send(_:) | Send an event to trigger a transition |
canSend(_:) | Check if an event is valid in the current state |
onTransition(_:) | Register a callback for state changes |
currentState | The current state |
| Property | Description |
|---|---|
from | Source state |
event | Triggering event |
to | Destination state |
sideEffect | Optional async closure executed during transition |
| Property/Method | Description |
|---|---|
state | Current state (observable) |
isTransitioning | Whether a transition is in progress |
send(_:) | Send an event |
canSend(_:) | Check if an event is valid |
swift build
swift test
💬 Bluesky · 🐦 X · 💼 LinkedIn · 🌐 Website · 📦 GitHub · ☕ Buy Me a Coffee · ❤️ GitHub Sponsors