Classes
The following classes are available globally.
-
The “machine” part of our finite state machine.
Given a
Transitionable
typeState
, this class holds its current value in the propertystate
and manages transitions to new states by consultingstate
’sshouldTransition(to:)
method.let stateMachine = StateMachine(initialState: MyState.ready) stateMachine.transition(to: .working) stateMachine.state // If `state.shouldTransition(to: .working)` // returns `true`, this will be `.working`. // Otherwise it will be `.ready`.
This class also publishes state changes to subscribers via
publisher
:let stateMachine = StateMachine(initialState: MyState.ready) stateMachine.publisher.sink { from, to in // from == .ready, to == .working if // ready -> working is a valid transition } stateMachine.transition(to: .working)
Property Wrapper
StateMachine
can also be used as a property wrapper, in which case the wrapped property’s type is the state type conforming toTransitionable
, its default value is the initial state, its projected value is itspublisher
, and all assignment happens throughtransition(to:)
. The above example could be written as:
See more@StateMachine var stateMachine: MyState = .ready $stateMachine.sink { from, to in // from == .ready, to == .working if // ready -> working is a valid transition } stateMachine = .working
Declaration
Swift
@propertyWrapper public class StateMachine<State> where State : Transitionable