从泛型类传递自引用

时间:2015-03-12 08:19:00

标签: cocoa swift

我想知道如何从泛型类传递self引用。换句话说,我如何在以下代码中删除AnyObject

protocol StateControllerDelegate: class {

    typealias StateType

    func stateController(stateController: AnyObject, didTransitionFromState fromState: StateType, toState: StateType)

}

class StateController<StateControllerDelegateType: StateControllerDelegate> {

    var delegate: StateControllerDelegateType?

}

谢谢!

1 个答案:

答案 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>的上下文中)。