加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 如何列出对象符合的协议?

发布时间:2020-12-14 05:01:18 所属栏目:百科 来源:网络整理
导读:使用Objective-C运行时,我可以获得一个对象符合的所有@objc协议的列表: let obj = NSObject()var pc: UInt32 = 0let plist = class_copyProtocolList(object_getClass(obj),pc)print("(obj.dynamicType) conforms to (pc) protocols")for i in 0 .. Int(p
使用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",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(协议)* 2(因为MyClass符合Equatable和Hashable).

是否有运行时公开的接口来获取对象符合的协议列表?

解决方法

你不能.不是ObjC的Swift协议只存在于编译时,并且实际上并不存在于对象本身上(这就是为什么根据变量的类型静态调度它们的方法的原因).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读