我想知道如何从泛型类传递self
引用。换句话说,我如何在以下代码中删除AnyObject
?
protocol StateControllerDelegate: class {
typealias StateType
func stateController(stateController: AnyObject, didTransitionFromState fromState: StateType, toState: StateType)
}
class StateController<StateControllerDelegateType: StateControllerDelegate> {
var delegate: StateControllerDelegateType?
}
谢谢!
答案 0 :(得分:1)
试试这个。
protocol StateControllerDelegate: class {
typealias StateType
func stateController(stateController: StateController<Self>, didTransitionFromState fromState: StateType, toState: StateType)
var fromState: StateType { get }
var toState: StateType { get }
}
class StateController<StateControllerDelegateType: StateControllerDelegate> {
var delegate: StateControllerDelegateType?
func callDelegate() {
delegate!.stateController(self,
didTransitionFromState: delegate!.fromState,
toState: delegate!.toState)
}
}
final class MyDelegate: StateControllerDelegate {
typealias StateType = Int
func stateController(stateController: StateController<MyDelegate>, didTransitionFromState fromState: StateType, toState: StateType) {
println("fromState=\(fromState), toState=\(toState)")
}
var fromState: StateType { return 0; }
var toState: StateType { return 1; }
}
let ctrl = StateController<MyDelegate>()
ctrl.delegate = MyDelegate()
ctrl.callDelegate()
修改强>;我想为重要的一点留下解释。
我将MyDelegate
作为final
课程,因为如果我不这样做,StateController<Self>
上下文MyDelegate
表示StateController<T>
(其中{ {1}}可以是继承T
)的任何类型,因此函数签名中的MyDelegate
不符合StateController<MyDelegate>
。目前,Swift不支持任何协方差/逆变量功能,因此使StateController<Self>
与StateController<Y>
兼容(StateController<X>
扩展Y
)是不可能的。但是,一旦我将X
添加到课程final
,现在MyDelegate
仅表示StateController<Self>
(在StateController<MyDelegate>
的上下文中)。