如何在Swift 4中获取类属性列表?

时间:2017-10-10 20:27:24

标签: swift

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]。

2 个答案:

答案 0 :(得分:2)

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

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"]

答案 1 :(得分:0)

您可以使用此:

extension NSObject {
    func propertyNames() -> [String] {
        let mirror = Mirror(reflecting: self)
        return mirror.children.compactMap{ $0.label }
    }
}
相关问题