cocoa - 从泛型类传递自引用

标签 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?

}

谢谢!

最佳答案

试试这个。

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

关于cocoa - 从泛型类传递自引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29004846/

相关文章:

Swift 将 Metal 着色器包含到库中 [使用 swift 包管理器]

ios - 为什么我的状态栏没有改变首选样式?

ios - Swift iOS - 从主队列函数内部调用主队列函数的区别?

iphone - SystemSoundID 的不同实例在不同的流上播放!

cocoa - 设置和维护 NSTableView 的第一个 SortDescriptor

objective-c - 为什么我在此 Cocoa 代码中收到 isEqualToString 错误?

objective-c - 将不同种类的项目共享到 NSSharingServicePicker?

ios - SWIFT iOS 中未调用委托(delegate)

iOS/Swift UIImageView (.jpg) 无法识别我的点击手势?

cocoa 选择器问题