我想知道如何从通用类传递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的上下文中)。

10-04 23:04