Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ynagatomo/14e670d62fc89bb19249fa8ef9f6e948 to your computer and use it in GitHub Desktop.
Save ynagatomo/14e670d62fc89bb19249fa8ef9f6e948 to your computer and use it in GitHub Desktop.
// Type-safe State Machine with Phantom Type May 2022 @AtarayoSD
import Foundation
protocol State {}
// Transitions
protocol TransferableToB {}
protocol TransferableToC {}
protocol TransferableToD {}
// States
enum StateA: State, TransferableToB, TransferableToC {}
enum StateB: State, TransferableToC, TransferableToD {}
enum StateC: State {}
enum StateD: State {}
// State Machine
final class StateMachine<T: State> {
init() {}
}
extension StateMachine where T == StateA {
var transitionX: StateMachine<StateB> {
print("=> State B")
return StateMachine<StateB>()
}
var transitionY: StateMachine<StateC> {
print("=> State C")
return StateMachine<StateC>()
}
}
extension StateMachine where T == StateB {
var transitionZ: StateMachine<StateC> {
print("=> State C")
return StateMachine<StateC>()
}
var transitionW: StateMachine<StateD> {
print("=> State D")
return StateMachine<StateD>()
}
var transitionQ: StateMachine<StateB> {
print("=> State B")
return StateMachine<StateB>()
}
}
extension StateMachine where T == StateC {
}
extension StateMachine where T == StateD {
}
final class Something {
func start() -> StateMachine<StateA> {
return StateMachine<StateA>()
}
}
let something = Something()
print("State A")
let stateMachine = something.start().transitionX.transitionQ.transitionW
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment