Swift协议MetaType的运行时比较

时间:2015-08-12 22:35:03

标签: swift swift2

我正在尝试动态地将Swift协议与实现匹配,但是我在尝试在运行时执行Protocols的比较时遇到了阻塞 - 似乎协议在运行时并不存在? 我试过的一些例子: var协议[任意] func findProtocol(aProtocol:Any) - >布尔{     //不,协议不实现equatable     aProtocol ==协议[0]     //不起作用,unsafeAddressOf()仅适用于AnyObjects     let pointer:UnsafePointer = unsafeAddressOf(aProtocol) } 我想我可能已经达到了试图击败类型系统的界限......任何想法?

2 个答案:

答案 0 :(得分:1)

我可能会稍微误解你的目标,但你应该能够使用反射。这样的事情怎么样?

protocol One {}
protocol Two {}
protocol Three {}

var protocols: [Any] = [One.self, Two.self]

func findProtocol(aProtocol: Any) -> Bool {

    let findMirror = Mirror(reflecting: aProtocol)

    for checkProtocol in protocols {
        let mirror = Mirror(reflecting: checkProtocol)

        if findMirror.subjectType == mirror.subjectType {
            return true
        }
    }
    return false
}

findProtocol(One) // Returns true
findProtocol(Two) // Returns true
findProtocol(Three) // Returns false

答案 1 :(得分:1)

如果您知道自己比较类型,则应使用更合适的类型(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
    }
}