State machine on Swift4.0
1. Create an Int
enumeration that abides on the Stateable
protocol
enum State: Int, Stateable {
case getUp
case eat
case sleep
// case getUp = 1 ❌ Do not set the value!!!
}
2. Use the enumeration to create a "Sprocket" and set its default state (idle)
let sprocket = Sprocket<State>(idle: .getUp)
3. Set its rules
sprocket.rules = [
[.sleep] >>> .getUp,
[.getUp] >>> .eat,
[.eat] >>> .sleep,
// if `[] >>> .getUp`, then any state can't to getUp
// if you don't set rule for some state, then any state can to the state
]
4. Set up its state listening
sprocket.before { (from, to) in }
sprocket.on { (from, to) in }
sprocket.after { (from, to) in }
you can listen to a single state also
sprocket.before(.getUp) { from in }
sprocket.on(.getUp) { from in }
sprocket.after(.getUp) { from in }
5. Use func to:
to switch state
sprocket.to(.eat)
To run the example project, clone the repo, and run pod install
from the Example directory first.
Sprocket is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'Sprocket'
Sprocket is available under the MIT license. See the LICENSE file for more info.