/
StateMachine.swift
49 lines (40 loc) · 1015 Bytes
/
StateMachine.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// StateMachine.swift
// StateMachine
//
// Created by iShawnWang on 2017/7/10.
// Copyright © 2017年 iShawnWang. All rights reserved.
//
import Foundation
// MARK: Delegate
public protocol StateMachineDelegate{
associatedtype State
func canEnter(state:State) -> Bool
func transit(from:State?, to:State)
}
/// Protocol Default Impl
extension StateMachineDelegate{
func canEnter(state:State) -> Bool{
return true
}
}
// MARK: StateMachine
public class StateMachine<T:StateMachineDelegate> {
public let delegate:T
public init(delegate:T) {
self.delegate = delegate
}
public var currentState:T.State?{
didSet{
delegate.transit(from: nil, to: currentState!)
}
}
@discardableResult
public func enter(state:T.State) -> Bool {
if(!delegate.canEnter(state: state)){
return false
}
delegate.transit(from: currentState, to: state)
return true
}
}