gpt4 book ai didi

ios - Swift 3 中的状态机

转载 作者:行者123 更新时间:2023-11-28 15:30:13 24 4
gpt4 key购买 nike

有没有人有一个可以用 Swift 实现的简单状态机的例子?我一直在谷歌搜索,但只看到了很多对我来说非常不透明的第三方库。我还看到很多高级讨论,人们在这些讨论中谈论 状态机,但没有显示任何代码。有人可以做一个简单的反例吗(比如加 1/减 1)?或者给我指一个?我知道这是一个很大的问题,但我的 google-fu 让我失望了。谢谢。

最佳答案

Apple 的 GamePlayKit 已经将状态机实现为 GKStateMachine。但是 GamePlayKit 仅适用于 iOS 9,因此我必须克隆 GKStateMachine(和 GKState)以在我的一个应用程序中支持 iOS 8。希望对您有所帮助。

EHStateMachine.swift

import Foundation


class EHStateMachine {
private(set) var currentState: EHState?
private let states = NSMapTable<AnyObject, EHState>(keyOptions: [.objectPointerPersonality],
valueOptions: [.strongMemory])

// MARK:

init(states: [EHState]) {
guard states.count > 0 else {
fatalError("Can't create state machine with zero states.")
}

let tempStates = NSHashTable<AnyObject>(options: [.objectPointerPersonality])

for state in states {
guard !tempStates.contains(type(of: state)) else {
fatalError("Duplicate instances of \(type(of: state)) found.")
}

tempStates.add(type(of: state))
}

for state in states {
state.stateMachine = self
self.states.setObject(state, forKey: type(of: state))
}
}

// MARK:

func canEnterState(_ stateClass: AnyClass) -> Bool {
if (states.object(forKey: stateClass) == nil) {
return false
}

if currentState == nil {
return true
}

return currentState!.isValidNextState(stateClass)
}

func enter(_ stateClass: AnyClass) -> Bool {
if !canEnterState(stateClass) {
return false
}

let previousState = currentState
let nextState = states.object(forKey: stateClass)

previousState?.willExit(to: nextState!)
currentState = nextState
currentState!.didEnter(from: previousState)

return true
}

func update(deltaTime seconds: TimeInterval) {
currentState?.update(deltaTime: seconds)
}

func state<T: EHState>(forClass stateClass: T.Type) -> T? {
return states.object(forKey: stateClass) as? T
}
}

EHState.swift

import Foundation


class EHState {

weak var stateMachine: EHStateMachine?

// MARK:

func isValidNextState(_ stateClass: AnyClass) -> Bool {
return true
}

func didEnter(from previousState: EHState?) {

}

func willExit(to nextState: EHState) {

}

func update(deltaTime seconds: TimeInterval) {

}
}

如果您的目标是 iOS 9,您可能应该使用 GKStateMachineGKState 而不是这些。

关于ios - Swift 3 中的状态机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44792041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com