-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathStateMachine.swift
More file actions
63 lines (47 loc) · 1.35 KB
/
Copy pathStateMachine.swift
File metadata and controls
63 lines (47 loc) · 1.35 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// StateMachine.swift
// Hummingbird
//
// Created by Sven A. Schmidt on 16/09/2019.
// Copyright © 2019 finestructure. All rights reserved.
//
// Based on https://www.figure.ink/blog/2015/2/9/swift-state-machines-part-4-redirect
import Foundation
enum Decision<T> {
case `continue`
case abort
case redirect(T)
}
protocol TransitionDelegate {
func shouldTransition(from: Self, to: Self) -> Decision<Self>
}
protocol StateMachineDelegate: class {
associatedtype State: TransitionDelegate
func didTransition(from: State, to: State)
}
class StateMachine<Delegate: StateMachineDelegate> {
private unowned let delegate: Delegate
private var _state: Delegate.State {
didSet {
delegate.didTransition(from: oldValue, to: _state)
}
}
var state: Delegate.State {
get { return _state }
set {
switch state.shouldTransition(from: _state, to: newValue) {
case .continue:
_state = newValue
case .redirect(let newState):
_state = newValue
self.state = newState
case .abort:
break
}
}
}
init(initialState: Delegate.State, delegate: Delegate) {
self._state = initialState
self.delegate = delegate
}
}