gpt4 book ai didi

cocoa - 从泛型类传递自引用

转载 作者:行者123 更新时间:2023-11-30 10:18:09 26 4
gpt4 key购买 nike

我想知道如何从泛型类传递 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com