Created
October 20, 2023 11:47
-
-
Save silverhammermba/ce9e3df3aabdfe5e880514f81091857f to your computer and use it in GitHub Desktop.
Swift state machine example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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