Latest 1.0.0
License MIT
Platforms ios 10.0, osx 10.12, watchos 3.0, tvos 10.0

Build Status  
CocoaPod platform  
CocoaPod version  
Carthage compatible


A state machine implemented in Swift.



  pod 'JCStateMachine', '~> 1.0.0'


  carthage 'jbaptistecastro/StateMachine' "1.0.0"



A state only needs a name.

Create a State object
let myState = State("MyState")


A transition needs a name, a "from" state and a "to" state.

Create a Transition object
let fromState = State("FromState")
let toState = State("ToState")

let myTransition = Transition("MyTransition", from: fromState, to: toState)

Lifecycle Events

Before a specific transition
On leaving a specific state
On entering in a specific state
On entering in a specific transition


A state machine takes an initial State and a Transition array.

Create a StateMachine object
let stateA = State("StateA")
let stateB = State("StateB")

let transitionA = Transition("TransitionA", from: stateA, to: stateB)
let transitionB = Transition("TransitionB", from: stateB, to: stateA)

let stateMachine = StateMachine(initialState: stateA, transitions: [transitionA, transitionB]
Fire a Transition
do { transitionB, userInfo: nil)
} catch TransitionError.unknown {
    print("Transition unknown)
} catch TransitionError.notAllowed {
    print("Transition not allowed")
Observe a lifecycle event

An event can be observed on a specific queue and can be triggered with a "userInfo" dictionary.

stateMachine.on(.onState(stateB), queue: observeQueue) { (userInfo) in


Helper functions

Compare a state with the current state
let isCurrent = stateMachine.isCurrent(state: myState)
If a transition can be fired
let canFire = stateMachine.canFire(transition: myTransition)
Get allowed transitions from the current state
let allowedTransitions = stateMachine.allowedTransitions()
Get a state from a specific name
let stateA = stateMachine.state(name: "stateA")
Get registered states
let states = stateMachine.allStates()
Get a transition from a specific name
let transitionA = stateMachine.transition(name: "transitionA")
Get registered transitions
let transitions = stateMachine.allTransitions()

Objective C compatibility

Actually, StateMachine doesn’t support Objective C and there is no plan to support it.

Latest podspec

    "name": "JCStateMachine",
    "version": "1.0.0",
    "summary": "A thread safe state machine implemented in pure Swift",
    "homepage": "",
    "license": {
        "type": "MIT"
    "authors": {
        "Jean-Baptiste Castro": "[email protected]"
    "social_media_url": "",
    "platforms": {
        "ios": "10.0",
        "osx": "10.12",
        "watchos": "3.0",
        "tvos": "10.0"
    "source": {
        "git": "",
        "tag": "1.0.0"
    "source_files": "Sources/**/*.swift",
    "module_name": "StateMachine"

Pin It on Pinterest

Share This