简体   繁体   中英

Runtime comparison of Swift Protocol MetaTypes

I'm trying to dynamically match a Swift protocol to an implementation, but I've gotten blocked on trying to perform comparisons of Protocols at runtime - it seems that maybe protocols don't really exist at runtime?

Some examples of things I've tried:

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) 

}

I think I might have hit the boundaries of trying to defeat the type system... any thoughts?

I may be slightly misunderstanding what you're looking to do, but you should be able to use reflection for this. How about something like this?

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

If you know that you compare the types themselves you should use a more appropriate type ( 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 }
}

For Any type you have to cast it:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM