Skip to content

Instantly share code, notes, and snippets.

@lilyball
Last active March 13, 2019 22:12
Show Gist options
  • Save lilyball/bbd827e6547226bf32230170cbedf670 to your computer and use it in GitHub Desktop.
Save lilyball/bbd827e6547226bf32230170cbedf670 to your computer and use it in GitHub Desktop.
class ViewControllerStandIn {
var stateMachine: StateMachine<State>
init(withSomething: Bool) {
if withSomething {
let delegate = FirstDelegate()
self.stateMachine = StateMachine(withInitialState: .A, callback: delegate.didTransitionFrom(from:to:))
} else {
let delegate = SecondDelegate()
self.stateMachine = StateMachine(withInitialState: .B, callback: delegate.didTransitionFrom(from:to:))
}
}
}
enum State {
case A
case B
func toString() -> String {
switch self {
case .A:
return "State A"
case .B:
return "State B"
}
}
}
class StateMachine<StateType> {
private let callback: (StateType, StateType) -> Void
var state: StateType {
didSet {
callback(oldValue, state)
}
}
init(withInitialState initialState: StateType, callback: @escaping (_ oldState: StateType, _ newState: StateType) -> Void) {
self.state = initialState
self.callback = callback
}
}
class FirstDelegate {
func didTransitionFrom(from: State, to: State) {
print("First Delegate going from " + from.toString() + " to " + to.toString())
}
}
class SecondDelegate {
func didTransitionFrom(from: State, to: State) {
print("Second Delegate going from " + from.toString() + " to " + to.toString())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment