A state machine implemented in Swift.
pod 'JCStateMachine', '~> 1.0.0'
carthage 'jbaptistecastro/StateMachine' "1.0.0"
A state only needs a name.
let myState = State("MyState")
A transition needs a name, a "from" state and a "to" state.
let fromState = State("FromState")
let toState = State("ToState")
let myTransition = Transition("MyTransition", from: fromState, to: toState)
beforeTransition(transition)
leaveState(state)
onState(state)
onTransition(transition)
A state machine takes an initial State and a Transition array.
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]
do {
stateMachine.fire(transition: transitionB, userInfo: nil)
} catch TransitionError.unknown {
print("Transition unknown)
} catch TransitionError.notAllowed {
print("Transition not allowed")
}
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
}
let isCurrent = stateMachine.isCurrent(state: myState)
let canFire = stateMachine.canFire(transition: myTransition)
let allowedTransitions = stateMachine.allowedTransitions()
let stateA = stateMachine.state(name: "stateA")
let states = stateMachine.allStates()
let transitionA = stateMachine.transition(name: "transitionA")
let transitions = stateMachine.allTransitions()
Actually, StateMachine doesn't support Objective C and there is no plan to support it.