Created
July 1, 2015 18:49
-
-
Save brianpartridge/7ed5be338f35b7d14d19 to your computer and use it in GitHub Desktop.
Swift StateMachine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol StateMachine { | |
typealias State | |
var state: State { get } | |
func canTransitionToState(newState: State) -> Bool | |
func transitionToState(newState: State) // throws, in Swift 2 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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