Search code examples
swiftreflectionmirror

Swift Mirror API - Which protocols an object conforms to


Is there a Swift Mirror API call that can tell me what protocols an object conforms to, ie:

protocol ProtocolA {}
protocol ProtocolB {}
protocol ProtocolC {}

class User : A, C {}

Then if I had the following code, it would print out A & C

let u = User()
let mirror = Mirror(reflecting: u)
let protocols = mirror.whichProtocols() // Made up code
print(protocols) //A & C

Solution

  • Not possible at all in Swift. Swift reflection is a very limited affair. If you are willing to bridge your class into ObjC, you can use the ObjC Runtime functions to get what you want:

    @objc protocol ProtocolA {}
    @objc protocol ProtocolB {}
    @objc protocol ProtocolC {}
    
    class User : NSObject, ProtocolA, ProtocolC {}
    
    var count: UInt32 = 0
    let protocols = class_copyProtocolList(User.self, &count)
    
    for i in 0..<Int(count) {
        let cname = protocol_getName(protocols[i])
        let name = String.fromCString(cname)
    
        print(name)
    }
    

    Each of your protocol must be prefixed with @objc and your class must inherit from NSObject.