Skip to content

Instantly share code, notes, and snippets.

@nixzhu
Last active February 25, 2020 14:27
Show Gist options
  • Save nixzhu/3f6dfd063f784269a29320b8d38e1719 to your computer and use it in GitHub Desktop.
Save nixzhu/3f6dfd063f784269a29320b8d38e1719 to your computer and use it in GitHub Desktop.
struct StateMachine<State, Action> {
private(set) var state: State
private let transition: (State, Action) -> State?
init(startState: State, transition: @escaping (State, Action) -> State?) {
self.state = startState
self.transition = transition
}
mutating func apply(action: Action) -> Bool {
if let nextState = transition(state, action) {
state = nextState
return true
}
return false
}
}
struct Light {
enum State {
case on, off, broken
}
enum Action {
case turn, cut
}
private var sm = StateMachine<State, Action>(startState: .off) { state, action -> State? in
switch (state, action) {
case (.off, .turn): return .on
case (.on, .turn): return .off
case (_, .cut): return .broken
default: return nil
}
}
var state: State {
return sm.state
}
@discardableResult
mutating func apply(action: Action) -> Bool {
return sm.apply(action: action)
}
}
var light = Light()
light.apply(action: .turn)
light.state
light.apply(action: .turn)
light.state
light.apply(action: .turn)
light.state
light.apply(action: .cut)
light.state
light.apply(action: .cut)
light.state
light.apply(action: .turn)
light.state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment