gpt4 book ai didi

swift - 协议(protocol)一致性检查

转载 作者:搜寻专家 更新时间:2023-11-01 05:31:47 26 4
gpt4 key购买 nike

如何使用 AssociatedType 对协议(protocol)执行一致性检查。 Xcode 显示错误:

Protocol 'MyListener' can only be used as a generic constraint because it has Self or associated type requirements

我的最终目标是从弱对象数组中提取“MyListener.section”,其中处理程序与函数参数匹配。

注意。 weakObjects 的 NSPointerArray 应该捕获不同类型的 MyListeners。

public class MyHandler<O,E> {
var source = [O]()
var dest = [E]()
}
public protocol MyListener:class {
var section: Int {get}
associatedtype O
associatedtype E
var handler: MyHandler<O,E>? { get }
}

public class MyAnnouncer {
private let mapWeakObjects: NSPointerArray = NSPointerArray.weakObjects()
public func add<L: MyListener>(listener: L) {
let pointer = Unmanaged.passUnretained(listener).toOpaque()
mapWeakObjects.addPointer(pointer)
}
public func search<O, E> (h:MyHandler<O,E>) -> [Int] {
_ = mapWeakObjects.allObjects.filter { listener in
if listener is MyListener { // Compilation failed
}
if let _ = listener as? MyListener { //Compilation error
}
if listener is MyListener.Type { //Compilation failed
}
}
return [] // ultimate goal is to extract corresponding [MyListener.section].
}
}

最佳答案

不幸的是,Swift 不支持与 AssociatedType 一致的协议(protocol)。

你应该尝试使用 Type Erasure .其中一种方法是通过创建新的 AnyType 类来实现类型删除。这是释放类型删除的另一种方法(来自互联网的示例)

protocol SpecialValue { /* some code*/ }

protocol TypeErasedSpecialController {
var typeErasedCurrentValue: SpecialValue? { get }
}

protocol SpecialController : TypeErasedSpecialController {
associatedtype SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}

extension SpecialController {
var typeErasedCurrentValue: SpecialValue? { return currentValue }
}

extension String : SpecialValue {}

struct S : SpecialController {
var currentValue: String?
}

var x: Any = S(currentValue: "Hello World!")
if let sc = x as? TypeErasedSpecialController { // Now we can perform conformance
print(sc.typeErasedCurrentValue)
}

关于swift - 协议(protocol)一致性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57676083/

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