【发布时间】:2015-01-29 11:46:17
【问题描述】:
我有一个类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 关联到 StateMachine 类中,但我不确定如何执行此操作,或者是否可能。我试过了:
class StateMachine<S: StateType, D: StateMachineDelegate where D.S == S> {
...
weak var delegate: D?
...
}
但后来我被困在试图重新设计协议以正确声明StateMachine 的泛型类型。在创建StateMachine 时,必须预先声明委托的类型似乎并不正确。
【问题讨论】:
标签: generics swift delegates protocols