协议一致性检查

时间:2019-08-27 13:46:20

标签: swift swift-protocols conditional-operator associated-types

如何针对具有AssociatedType的协议执行一致性检查。 Xcode显示错误:

  

协议“ MyListener”只能用作通用约束,因为   有自我或相关类型要求

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

注意。假设弱对象的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].
    }
}

1 个答案:

答案 0 :(得分:0)

不幸的是,Swift不支持带有AssociatedType的协议。

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

using (var _context = new MyContext(@"server=....){
context.Table1....
}
相关问题