StateMachine
Swift library to create Finite-state machines inspired by GKStateMachine from Apple GameplayKit framework.
Test StateMachine working live!
🌟 Features
- Define States and Their Behavior.
- Create and Drive a State Machine.
- Subscribe/unsubscribe to State changes.
- UIApplication and UIApplicationDelegate extensions with application life cycle State Machine embedded.
- StatefulViewController subclass with UIViewController life cycle State Machine embedded.
📲 Installation
StateMachine is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'ArchitStateMachine'
Carthage:
Or you can install it withgithub "alexruperez/StateMachine"
Swift Package Manager:
Or install it withdependencies: [
.package(url: "https://github.com/alexruperez/StateMachine.git")
]
🐒 Usage
Define States and Their Behavior:
class MyState: State {
func isValidNext<S>(state type: S.Type) -> Bool where S : State {
switch type {
case is OneValidNextState.Type, is OtherValidNextState.Type:
return true
default:
return false
}
}
}
class OneValidNextState: State {
func isValidNext<S>(state type: S.Type) -> Bool where S : State {
return type is OtherValidNextState.Type
}
func didEnter(from previous: State?) {
// Your code here
}
}
class OtherValidNextState: State {
func isValidNext<S>(state type: S.Type) -> Bool where S : State {
return false
}
func willExit(to next: State) {
// Your code here
}
}
Create and Drive a State Machine:
let stateMachine = StateMachine([MyState(), OneValidNextState(), OtherValidNextState()])
stateMachine.enter(OneValidNextState.self)
stateMachine.enter(OtherValidNextState.self)
Subscribe/unsubscribe to State changes:
let subscriptionToken = stateMachine.subscribe { (previous, current) in
// Your code here
}
stateMachine.unsubscribe(subscriptionToken)
stateMachine.unsubscribeAll()
UIApplication and UIApplicationDelegate extensions with application life cycle State Machine embedded:
if UIApplication.shared.stateMachine.current is ActiveApplicationState {
// Your code here
}
StatefulViewController subclass with UIViewController life cycle State Machine embedded:
let viewController = StatefulViewController()
if viewController.stateMachine.current is AppearingViewControllerState {
// Your code here
}
❤️ Etc.
- Contributions are very welcome.
- Attribution is appreciated (let's spread the word!), but not mandatory.
👨💻 Authors
alexruperez, contact@alexruperez.com
👮♂️ License
StateMachine is available under the MIT license. See the LICENSE file for more info.