JAL*_*JAL 6 protocols objective-c-runtime swift swift-protocols
使用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])]))
}
Run Code Online (Sandbox Code Playgroud)
或者运行时加载的所有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])]))
}
Run Code Online (Sandbox Code Playgroud)
但这些都没有列出任何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
Run Code Online (Sandbox Code Playgroud)
strProtocols当我希望它返回时sizeof(Protocol) * 2(因为MyClass符合Equatable和Hashable),它是0 .
是否有运行时公开的接口来获取对象符合的协议列表?
你不能 不是ObjC协议的Swift协议仅在编译时存在,并且在对象本身上并不存在(这就是为什么根据变量的类型静态分配其方法的原因)。
| 归档时间: |
|
| 查看次数: |
1041 次 |
| 最近记录: |