Skip to content

Instantly share code, notes, and snippets.

@brianpartridge
Created July 1, 2015 18:49
Show Gist options
  • Save brianpartridge/7ed5be338f35b7d14d19 to your computer and use it in GitHub Desktop.
Save brianpartridge/7ed5be338f35b7d14d19 to your computer and use it in GitHub Desktop.
Swift StateMachine
protocol StateMachine {
typealias State
var state: State { get }
func canTransitionToState(newState: State) -> Bool
func transitionToState(newState: State) // throws, in Swift 2
}
class Transmission : StateMachine {
typealias State = TransmissionState
internal private(set) var state: State = .Parked
internal func canTransitionToState(newState: State) -> Bool {
switch newState {
case .Parked, .Drive, .Reverse:
return state == .Neutral
case .Neutral:
return state != .Neutral
}
}
internal func transitionToState(newState: State) {
precondition(canTransitionToState(newState), "Unable to transition from \(state) to \(newState)")
state = newState
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment