Skip to content

Instantly share code, notes, and snippets.

@silverhammermba
Created October 20, 2023 11:47
Show Gist options
  • Save silverhammermba/ce9e3df3aabdfe5e880514f81091857f to your computer and use it in GitHub Desktop.
Save silverhammermba/ce9e3df3aabdfe5e880514f81091857f to your computer and use it in GitHub Desktop.
Swift state machine example
protocol State {
func nextState() -> Self
}
class StateMachine<T: State> {
private(set) var currentState: T
init(_ initialState: T) {
currentState = initialState
}
func nextState() -> T {
currentState = currentState.nextState()
return currentState
}
}
enum PlayerState: State {
case idle, walking
func nextState() -> PlayerState {
switch self {
case .idle:
return .walking
case .walking:
return .idle
}
}
}
let playerStateMachine = StateMachine<PlayerState>(.idle)
print(playerStateMachine.currentState) // idle
print(playerStateMachine.nextState()) // walking
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment