如何使用AssociatedType对协议执行一致性检查。Xcode显示错误:
协议'MyListener‘只能用作泛型约束,因为它具有自或关联的类型要求
我的最终目标是从一个weakObjects数组中提取“weakObjects”,其中处理程序与函数参数匹配。
请注意。NSPointerArray of weakObjects应该捕获不同类型的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].
}
}发布于 2019-08-27 20:46:54
不幸的是,Swift不支持与AssociatedType一致的协议。
您应该尝试使用类型擦除。其中一种方法是通过创建新的AnyType类来实现类型删除。下面是另一种发布类型擦除的方法(来自internet的示例)
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)
}https://stackoverflow.com/questions/57676083
复制相似问题