swift-state-machine-patterns
БесплатноБез исполняемых скриптовНе проверенBuild type-safe Swift state machines with enum states and action-based transitions. Use for lifecycle or protocol flows, reentrancy-sensitive operations, or…
от nonameplum★ 17 звёзд на GitHubОб этом скилле
Swift State Machine Patterns
When to use
- Reentrancy-sensitive flows
- Protocol or lifecycle logic with strict transition rules
- Async streams or continuations that need cancellation safety
- Boundaries where invalid state must be unrepresentable
Core rules
- Model state as an enum with associated values. Each case carries only data valid in that state.
- Keep the state machine as a value type (
struct) with a privatestate. - Transition methods are pure: mutate state and return
Actionvalues. - Execute side effects outside the transition (and outside any lock).
- Use strong types for events (enum or method parameters), actions, and identifiers. Avoid strings or boolean flags for state.
- Prefer per-state structs for larger associated data to prevent accidental access to irrelevant fields.
- Make invalid states unrepresentable by construction, not by runtime checks.
Sub-state pattern
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.
- Use one struct per state (
IdleState,ActiveState,QuiescingState). - Store only the fields valid in that state; move shared data into protocols.
- Use
init(from:)to build the next state from the prior one and copy only relevant fields. - Use capability protocols (e.g.,
MaySendFrames,HasLocalSettings) to keep helpers constrained to valid states. - Optional: a
modifyingsentinel 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)
}
Usage pattern: driver + state machine
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()
}
}
Pattern: Method-per-event (SwiftNIO style)
Model events as dedicated mutating methods (send/receive). Each method switches
on state and returns a typed result or actions. This mirrors
HTTP2ConnectionStateMachine 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:
- For complex inputs, use a nested
Requeststruct to keep method signatures small. - Share repeated transitions in private helpers that mutate state and return actions.
- Expose read-only query helpers (e.g.,
isConnected) as computed properties. - When each event returns a different shape, use per-event action enums
(
NextAction,FinishAction) instead of a single sharedAction. - Use a
.modifyingsentinel state to avoid CoW when updating associated data. - Trap impossible transitions with
preconditionFailureto keep invariants strict. - Track suspended and cancelled sets with placeholder IDs for out-of-order cancel.
- Model terminal outcomes with a
Terminationenum (e.g., finished vs failed). - Return optional actions when an event produces no side effects.
SwiftNIO-derived refinements
From NIOTypedHTTPClientUpgraderStateMachine and `NIO
Установить swift-state-machine-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл swift-state-machine-patterns?
Build type-safe Swift state machines with enum states and action-based transitions. Use for lifecycle or protocol flows, reentrancy-sensitive operations, or async/concurrent workflows.
Как установить скилл swift-state-machine-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swift-state-machine-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic