我想知道如何从通用类传递self
引用。换句话说,如何在以下代码中摆脱AnyObject
?
protocol StateControllerDelegate: class {
typealias StateType
func stateController(stateController: AnyObject, didTransitionFromState fromState: StateType, toState: StateType)
}
class StateController<StateControllerDelegateType: StateControllerDelegate> {
var delegate: StateControllerDelegateType?
}
谢谢!
最佳答案
尝试这个。
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>
(其中T
可以是继承MyDelegate
的任何类型),因此函数签名中的StateController<MyDelegate>
不符合StateController<Self>
。目前,Swift不支持任何类似协方差/相反的功能,因此使StateController<Y>
与StateController<X>
兼容(其中Y
扩展了X
)是不可能的。但是,一旦我将final
添加到类MyDelegate
中,现在StateController<Self>
就意味着StateController<MyDelegate>
(在MyDelegate
的上下文中)。