gpt4 book ai didi

swift - 如何获取 Swift 4 中的类属性列表?

转载 作者:可可西里 更新时间:2023-11-01 01:12:07 26 4
gpt4 key购买 nike

func getAllPropertyName(_ aClass : AnyClass) -> [String] {
var count = UInt32()
let properties = class_copyPropertyList(aClass, &count)
var propertyNames = [String]()
let intCount = Int(count)
for i in 0 ..< intCount {
let property : objc_property_t = properties![i]!
guard let propertyName = NSString(utf8String: property_getName(property)) as? String else {
debugPrint("Couldn't unwrap property name for \(property)")
break
}
propertyNames.append(propertyName)
}
free(properties)
return propertyNames

此代码在 Swift 3.2 之前有效。但我使用的是 Swift 4,它给了我一个空的 Array[String]。

最佳答案

您可以获得如下所示的属性:

class ClassTest {
var prop1: String?
var prop2: Bool?
var prop3: Int?
}

let mirror = Mirror(reflecting: ClassTest())
print(mirror.children.flatMap { $0.label }) // ["prop1", "prop2", "prop3"]

关于swift - 如何获取 Swift 4 中的类属性列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46675422/

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