swift - Swift 协议(protocol)元类型的运行时比较

标签 swift swift2

我正在尝试将 Swift 协议(protocol)与实现动态匹配,但我在尝试在运行时执行协议(protocol)比较时遇到了阻碍 - 似乎协议(protocol)在运行时可能并不存在?

我尝试过的一些例子:

var protocols[Any]

func findProtocol(aProtocol: Any) -> Bool {
    // Nope, protocols don't implement equatable
    aProtocol == protocols[0]

    // Doesn't work, unsafeAddressOf() only applies to AnyObjects
    let pointer: UnsafePointer = unsafeAddressOf(aProtocol) 

}

我想我可能已经触及了试图打败类型系统的界限……有什么想法吗?

最佳答案

如果您知道比较类型本身,您应该使用更合适的类型 (Any.Type):

var protocolArray: [Any.Type] = [...]

func findProtocol(aProtocol: Any.Type) -> Bool {
    // you can do that because Any.Type has an == operator
    return protocolArray.contains{ $0 == aProtocol }
}

对于 Any 类型,你必须转换它:

var protocolArray: [Any] = [...]

func findProtocol(aProtocol: Any) -> Bool {
    return protocolArray.contains{
        if let p1 = $0 as? Any.Type, p2 = aProtocol as? Any.Type {
            return p1 == p2
        }
        return false
    }
}

关于swift - Swift 协议(protocol)元类型的运行时比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976567/

相关文章:

ios - 检查自定义键盘中 documentContextBeforeInput 中的字符

ios - NSNotification 不重新加载表数据

swift - 通过调用 super : call can throw but is not marked with `try` 覆盖所需的 init

swift - 初始化器的结果未被使用

swift2 - 错误 'value of type Realm.Configuration' 没有成员路径',swift 2.2

ios - 为什么当我尝试获取边界时 previewLayer 返回 nil?

swift - UIActivityViewController 中的共享 WebView

ios - 获取深层链接 url iOS 中的参数值

ios - 快速添加子项目

ios - swift 2.0 中的关闭声明