Skip to content

A thread safe state machine implemented in pure Swift

License

Notifications You must be signed in to change notification settings

carabina/StateMachine-2

 
 

Repository files navigation

Build Status   CocoaPod platform   CocoaPod version   Carthage compatible

StateMachine

A state machine implemented in Swift.

Installation

CocoaPods

  pod 'JCStateMachine', '~> 1.0.0'

Carthage

  carthage 'jbaptistecastro/StateMachine' "1.0.0"

Classes

State

A state only needs a name.

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

Transition

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
beforeTransition(transition)
On leaving a specific state
leaveState(state)
On entering in a specific state
onState(state)
On entering in a specific transition
onTransition(transition)

StateMachine

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 {
    stateMachine.fire(transition: 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.

About

A thread safe state machine implemented in pure Swift

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 85.5%
  • Makefile 10.1%
  • Ruby 4.4%