gpt4 book ai didi

swift - 反射(reflection):在Swift中获取类的静态var?

转载 作者:行者123 更新时间:2023-11-28 07:53:57 25 4
gpt4 key购买 nike

给出一个简单的类,比如:

class Foo {
static var can: String? { didSet { 5+4 } }
static let haz: String
}

如何在 Foo中实现枚举 canhaz的方法,而不必再次显式地写出它们?-例如:这样我就可以 print("key: '\(key\)' has value: '\(value)'")
顺便说一句:注意到这一点: How to loop over struct properties in Swift?;但无法让它为 static工作。

最佳答案

您可以使用Objective-c运行时,特别是描述类声明的属性的函数class_copyPropertyList。例子:

import Foundation

class Foo:NSObject {
@objc static var prop1: String? = "Hello I am prop1!"
@objc static var prop2: String? = "Hello I am prop2!"
}

var count: CUnsignedInt = 0
let methods = class_copyPropertyList(object_getClass(Foo.self), &count)!
for i in 0 ..< count {
let selector = property_getName(methods.advanced(by: Int(i)).pointee)
if let key = String(cString: selector, encoding: .utf8) {
let res = Foo.value(forKey: key)
print("name: \(key), value: \(res ?? "")")
}
}

关于swift - 反射(reflection):在Swift中获取类的静态var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858619/

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