我一直在为Swift研究Apple的状态机,并找到了几个例子,但其中没有一个真的很简单。
有人可以在Swift中使用超级简单的GKStateMachine,也许有两个状态,最好是在一个Swift文件中?谢谢!
答案 0 :(得分:12)
以下是在美国工作的交通灯状态机的示例。红绿灯从green -> yellow -> red -> green
移动。
在应用中,您可能会让didEnter(from:)
例程更新屏幕图形,或允许其他演员移动。
import UIKit
import GameKit
class Green: GKState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is Yellow.Type
}
override func didEnter(from previousState: GKState?) {
print("Traffic light is green")
}
}
class Yellow: GKState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is Red.Type
}
override func didEnter(from previousState: GKState?) {
print("Traffic light is yellow")
}
}
class Red: GKState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is Green.Type
}
override func didEnter(from previousState: GKState?) {
print("Traffic light is red")
}
}
class ViewController: UIViewController {
var stateMachine: GKStateMachine?
override func viewDidLoad() {
super.viewDidLoad()
// Create the states
let green = Green()
let yellow = Yellow()
let red = Red()
// Initialize the state machine
stateMachine = GKStateMachine(states: [green, yellow, red])
// Try entering various states...
if stateMachine?.enter(Green.self) == false {
print("failed to move to green")
}
if stateMachine?.enter(Red.self) == false {
print("failed to move to red")
}
if stateMachine?.enter(Yellow.self) == false {
print("failed to move to yellow")
}
if stateMachine?.enter(Green.self) == false {
print("failed to move to green")
}
if stateMachine?.enter(Red.self) == false {
print("failed to move to red")
}
}
}
输出:
Traffic light is green failed to move to red Traffic light is yellow failed to move to green Traffic light is red