Last active
July 1, 2016 07:32
-
-
Save RyogaK/872afb682115fc263730b6069344cc5d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// StateMachine.swift | |
// | |
// Created by Ryoga Kitagawa on 5/6/16. | |
// | |
protocol StateMachineEvent {} | |
protocol StateMachineState {} | |
class StateMachine<S: StateMachineState, E: StateMachineEvent> { | |
var routes: (event: E, from: S) -> S? | |
var handler: ((event: E, from: S, to: S) -> ())? | |
private(set) var state: S | |
init(state: S, initClosure: ((StateMachine) -> ())? = nil) { | |
self.state = state | |
self.routes = { _ in state } | |
initClosure?(self) | |
} | |
func fireEvent(event: E) { | |
guard let nextState = self.routes(event: event, from: self.state) else { | |
fatalError() | |
} | |
self.handler?(event: event, from: self.state, to: nextState) | |
self.state = nextState | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment