Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chosa91/569b8b4366ef0df1ec241c429e0fc9c0 to your computer and use it in GitHub Desktop.
Save chosa91/569b8b4366ef0df1ec241c429e0fc9c0 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