【发布时间】:2016-03-24 14:59:25
【问题描述】:
使用 Objective-C 运行时,我可以获得对象符合的所有 @objc 协议的列表:
let obj = NSObject()
var pc: UInt32 = 0
let plist = class_copyProtocolList(object_getClass(obj), &pc)
print("\(obj.dynamicType) conforms to \(pc) protocols")
for i in 0 ..< Int(pc) {
print(String(format: "Protocol #%d: %s", arguments: [i, protocol_getName(plist[i])]))
}
或运行时加载的所有 Objective-C 协议:
var allProtocolCount: UInt32 = 0
let protocols = objc_copyProtocolList(&allProtocolCount)
print("\(allProtocolCount) total protocols")
for i in 0 ..< Int(allProtocolCount) {
print(String(format: "Protocol #%d: %s", arguments: [i, protocol_getName(protocols[i])]))
}
但这些都没有列出任何 Swift 协议:
func == (lhs: MyClass, rhs: MyClass) -> Bool {
return lhs.value == rhs.value
}
class MyClass: Equatable, Hashable {
var value: Int
var hashValue: Int {
return value
}
init(value: Int) {
self.value = value
}
}
var count: UInt32 = 0;
let strProtocols = class_copyProtocolList(MyClass.self, &count) // 0x0000000000000000
strProtocols 是 0,而我希望它返回 sizeof(Protocol) * 2(因为 MyClass 符合 Equatable 和 Hashable)。
是否有运行时公开的接口来获取对象符合的协议列表?
【问题讨论】:
标签: swift protocols objective-c-runtime swift-protocols