Swift 镜像 API - 对象符合哪些协议
Swift Mirror API - Which protocols an object conforms to
是否有 Swift 镜像 API 调用可以告诉我一个对象符合什么协议,即:
protocol ProtocolA {}
protocol ProtocolB {}
protocol ProtocolC {}
class User : A, C {}
那么如果我有下面的代码,它会打印出 A & C
let u = User()
let mirror = Mirror(reflecting: u)
let protocols = mirror.whichProtocols() // Made up code
print(protocols) //A & C
在 Swift 中根本不可能。 Swift 反思是一件非常有限的事情。如果你愿意将你的 class 桥接到 ObjC,你可以使用 ObjC Runtime functions 来获得你想要的:
@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)
}
您的每个协议都必须以 @objc
为前缀,并且您的 class 必须继承自 NSObject
。
是否有 Swift 镜像 API 调用可以告诉我一个对象符合什么协议,即:
protocol ProtocolA {}
protocol ProtocolB {}
protocol ProtocolC {}
class User : A, C {}
那么如果我有下面的代码,它会打印出 A & C
let u = User()
let mirror = Mirror(reflecting: u)
let protocols = mirror.whichProtocols() // Made up code
print(protocols) //A & C
在 Swift 中根本不可能。 Swift 反思是一件非常有限的事情。如果你愿意将你的 class 桥接到 ObjC,你可以使用 ObjC Runtime functions 来获得你想要的:
@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)
}
您的每个协议都必须以 @objc
为前缀,并且您的 class 必须继承自 NSObject
。