Classes

The following classes are available globally.

  • The “machine” part of our finite state machine.

    Given a Transitionable type State, this class holds its current value in the property state and manages transitions to new states by consulting state’s shouldTransition(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 to Transitionable, its default value is the initial state, its projected value is its publisher, and all assignment happens through transition(to:). The above example could be written as:

    @StateMachine var stateMachine: MyState = .ready
    $stateMachine.sink { from, to in
      // from == .ready, to == .working if
      // ready -> working is a valid transition
    }
    stateMachine = .working
    
    See more

    Declaration

    Swift

    @propertyWrapper
    public class StateMachine<State> where State : Transitionable