gpt4 book ai didi

swift - 如何列出对象符合的协议(protocol)?

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:53 25 4
gpt4 key购买 nike

使用 Objective-C 运行时,我可以获得对象符合的所有 @objc 协议(protocol)的列表:

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 协议(protocol):

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 协议(protocol):

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 符合 EquatableHashable)。

运行时是否公开了一个接口(interface)来获取对象符合的协议(protocol)列表?

最佳答案

你不能。不是 ObjC 协议(protocol)的 Swift 协议(protocol)只存在于编译时,并不真正存在于对象本身(这就是为什么它们的方法是根据变量的类型静态分派(dispatch)的)。

关于swift - 如何列出对象符合的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com