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

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

如何使用 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/

相关文章:

swift - 符合协议(protocol)——一次又一次地添加协议(protocol) stub 并不能修复错误

swift - 触摸手势识别器清除屏幕的随机功能

swift - 在 Swift 协议(protocol)中约束关联类型

Java 多个三元运算符

C++20 在三元语句中返回元组

ios - 当侧边栏处于事件状态时防止 TableView 滚动

ios - 在 UIPreviewAction 上添加图标或图像

ios - Swift - 调用自定义委托(delegate)方法

ios - 具有关联类型的 Functor 协议(protocol)的实现(Swift)

c++ - cout 语句中使用的条件运算符