This skill helps you implement type-safe Swift state machines with enum states and action-based transitions for robust concurrency and lifecycle flows.
npx playbooks add skill nonameplum/agent-skills --skill swift-state-machine-patterns
valid in that state.
struct) with a private state.Action values.identifiers. Avoid strings or boolean flags for state.
access to irrelevant fields.
Model each state as a dedicated struct and store it as an associated value in
the enum. Capabilities are expressed as protocols and only adopted by states
that support them.
IdleState, ActiveState, QuiescingState).init(from:) to build the next state from the prior one and copy onlyrelevant fields.
MaySendFrames, HasLocalSettings) to keephelpers constrained to valid states.
modifying sentinel state can avoid CoW during transitions.private struct IdleState: ConnectionStateWithRole, ConnectionStateWithConfiguration { /* ... */ }
private struct ActiveState: ConnectionStateWithRole, HasLocalSettings, HasRemoteSettings { /* ... */ }
private enum State {
case idle(IdleState)
case active(ActiveState)
}
Embed the state machine inside a handler/coordinator that owns side effects.
The driver calls transition methods, applies effects, and decides
whether to forward/emit/drop inputs.
final class ProtocolHandler {
private var stateMachine = ConnectionStateMachine()
private var pendingEvents: [UserEvent] = []
func receive(_ message: Message) {
let result = stateMachine.receive(message)
apply(effect: result.effect)
switch result.result {
case .succeed:
forward(message)
case .ignore:
break
case .connectionError(let error):
handleConnectionError(error)
case .streamError(let id, let error):
handleStreamError(id, error)
}
flushPendingEvents()
}
func send(_ message: Message) {
let result = stateMachine.send(message)
apply(effect: result.effect)
if case .succeed = result.result {
write(message)
} else {
handleSendError(result.result)
}
flushPendingEvents()
}
}
Model events as dedicated mutating methods (send/receive). Each method switches
on state and returns a typed result or actions. This mirrorsHTTP2ConnectionStateMachine in SwiftNIO HTTP/2.
struct ConnectionStateMachine: Sendable {
private enum State: Sendable {
case idle(IdleState)
case active(ActiveState)
case quiescing(QuiescingState)
}
private struct IdleState: Sendable { }
private struct ActiveState: Sendable { var streamID: Int }
private struct QuiescingState: Sendable { var lastStreamID: Int }
enum Action: Sendable {
case sendPreface
case closeStream(id: Int)
case ignore
}
private var state: State = .idle(IdleState())
mutating func receiveGoaway(lastStreamID: Int) -> [Action] {
switch state {
case .active(let data):
state = .quiescing(QuiescingState(lastStreamID: lastStreamID))
return lastStreamID < data.streamID ? [.closeStream(id: data.streamID)] : []
default:
return [.ignore]
}
}
mutating func sendPreface() -> [Action] {
switch state {
case .idle:
state = .active(ActiveState(streamID: 0))
return [.sendPreface]
default:
return [.ignore]
}
}
}
Notes:
Request struct to keep method signatures small.isConnected) as computed properties.(NextAction, FinishAction) instead of a single shared Action.
.modifying sentinel state to avoid CoW when updating associated data.preconditionFailure to keep invariants strict.Termination enum (e.g., finished vs failed).From NIOTypedHTTPClientUpgraderStateMachine and NIOTypedHTTPClientUpgradeHandler:
.awaitingResponseHead -> .awaitingResponseEnd -> .upgrading -> .unbuffering -> .finished.ChannelActiveAction, WriteAction, ChannelReadAction.preconditionFailure / fatalError) in debug paths.handlerRemoved/terminated event with explicit action to fail pending promises/tasks.struct ChannelStateMachine<Element: Sendable> {
private struct SuspendedProducer: Hashable {
let id: UInt64
let continuation: UnsafeContinuation<Void, Never>?
let element: Element?
static func placeHolder(id: UInt64) -> SuspendedProducer {
SuspendedProducer(id: id, continuation: nil, element: nil)
}
}
private struct SuspendedConsumer: Hashable {
let id: UInt64
let continuation: UnsafeContinuation<Element?, any Error>?
static func placeHolder(id: UInt64) -> SuspendedConsumer {
SuspendedConsumer(id: id, continuation: nil)
}
}
private enum State {
case channeling(
suspendedProducers: OrderedSet<SuspendedProducer>,
cancelledProducers: Set<SuspendedProducer>,
suspendedConsumers: OrderedSet<SuspendedConsumer>,
cancelledConsumers: Set<SuspendedConsumer>
)
case terminated(Termination)
}
enum SendAction { case suspend; case resumeConsumer(UnsafeContinuation<Element?, any Error>?) }
enum NextAction { case suspend; case resumeProducer(UnsafeContinuation<Void, Never>?, Result<Element?, Error>) }
enum SendCancelledAction { case none; case resumeProducer(UnsafeContinuation<Void, Never>?) }
mutating func send() -> SendAction { /* switch state */ }
mutating func next() -> NextAction { /* switch state */ }
mutating func sendCancelled(producerID: UInt64) -> SendCancelledAction { /* placeholders */ }
}
struct CombineLatestStateMachine<A: AsyncSequence, B: AsyncSequence, C: AsyncSequence?> {
typealias DownstreamContinuation = UnsafeContinuation<Result<(A.Element, B.Element, C.Element?)?, Error>, Never>
private enum State {
struct Upstream<Element> {
var continuation: UnsafeContinuation<Void, Error>?
var element: Element?
var isFinished: Bool
}
case initial(base1: A, base2: B, base3: C)
case waitingForDemand(task: Task<Void, Never>, upstreams: (Upstream<A.Element>, Upstream<B.Element>, Upstream<C.Element>), buffer: Deque<(A.Element, B.Element, C.Element?)>)
case combining(task: Task<Void, Never>, upstreams: (Upstream<A.Element>, Upstream<B.Element>, Upstream<C.Element>), downstreamContinuation: DownstreamContinuation, buffer: Deque<(A.Element, B.Element, C.Element?)>)
case upstreamsFinished(buffer: Deque<(A.Element, B.Element, C.Element?)>)
case upstreamThrew(error: Error)
case finished
case modifying
}
enum NextAction {
case startTask(A, B, C)
case resumeUpstreamContinuations([UnsafeContinuation<Void, Error>])
case resumeContinuation(DownstreamContinuation, Result<(A.Element, B.Element, C.Element?)?, Error>)
case resumeDownstreamContinuationWithNil(DownstreamContinuation)
}
mutating func next(for continuation: DownstreamContinuation) -> NextAction { /* switch state */ }
mutating func upstreamFinished(baseIndex: Int) -> UpstreamFinishedAction? { /* switch state */ }
}
Mutex (Synchronization) on iOS 18+ or NSRecursiveLock iOS 16+ or an actor.withTaskCancellationHandler when storing continuations so cancellationcan drive a state transition.
sendPreface,receiveGoaway).
Action array and the new state.isActive, isFinished, hasStarted)String or loosely-typed integersWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.