我有一堂课,StateMachine
,这是通用的,允许将不同的状态集实现为例如枚举。我想用一个StateMachineDelegate
当状态机进入新状态时通知委托的协议。
但这不起作用,因为委托协议对于类型要求也是通用的。该错误显示了哪里delegate
财产已申报。
protocol StateType: Hashable {}
protocol StateMachineDelegate: class {
typealias S: StateType
func stateMachine(stateMachine: StateMachine<S>, didEnterState newState: S)
}
class StateMachine<S: StateType> {
typealias State = S
weak var delegate: StateMachineDelegate?
//~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
//Protocol 'StateMachineDelegate' can only be used as a generic constraint because it has Self or associated type requirements
var currentState: State {...}
init(initialState: State) {...}
func applyState(toState: State) -> Bool {
...
currentState = toState
delegate?.stateMachine(self, didEnterState: toState)
...
}
}
我需要以某种方式将其关联起来StateMachineDelegate.S == S
in the StateMachine
类,但我不确定如何做到这一点,或者是否可能。我试过:
class StateMachine<S: StateType, D: StateMachineDelegate where D.S == S> {
...
weak var delegate: D?
...
}
但后来我陷入尝试修改协议以正确声明通用类型的困境StateMachine
。在创建委托时必须预先声明委托的类型似乎并不正确StateMachine
.
看看这个解决方法是否可以满足您的需求,它使用@autoclosure
解决递归泛型定义的问题:
class StateMachine<S: Printable, D: StateMachineDelegate where S == D.StateType> {
var currentState: S {
didSet {
// The observer
if let delegate = self.delegate {
delegate.stateMachine(self, didEnterState: self.currentState)
}
}
}
var delegate: D?
init(initialState: S) {
self.currentState = initialState
}
}
protocol StateMachineDelegate: class {
typealias StateType: Printable
// Workaround with autoclosure
func stateMachine(machine: @autoclosure() -> StateMachine<StateType, Self>, didEnterState newState: StateType)
}
final class ADelegate: StateMachineDelegate {
typealias StateType = Int
func stateMachine(machine: @autoclosure () -> StateMachine<StateType, ADelegate>, didEnterState newState: StateType) {
// Need to _unbox_ the sander from the closure
let sender = machine()
println(newState)
println("State from sender: \(sender.currentState)")
}
}
let stateMachine = StateMachine<Int, ADelegate>(initialState: 24)
stateMachine.delegate = ADelegate()
stateMachine.currentState = 50
顺便说一下,考虑一下,如果你得到了砂光机,可能你就不需要得到newState
通过了。
我用了Printable
代替Hashable
例如。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)