7
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

This code work till Swift 3.2. But I'm using Swift 4 and it's giving me an empty Array[String].

  • 1
    See https://stackoverflow.com/q/44762460/1187415 and https://stackoverflow.com/q/44390378/1187415: You explicitly must expose members to the Objective-C runtime with `@objc` in Swift 4. – Martin R Oct 10 '17 at 20:36
  • Possible duplicate of [List of class's properties in swift](https://stackoverflow.com/questions/24844681/list-of-classs-properties-in-swift) – Ibo Oct 11 '17 at 02:13

2 Answers2

9

You can get `properties like below :

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"]
Vini App
  • 7,339
  • 2
  • 26
  • 43
4

You can use this:

extension NSObject {
    func propertyNames() -> [String] {
        let mirror = Mirror(reflecting: self)
        return mirror.children.compactMap{ $0.label }
    }
}
Zaldy Bughaw
  • 797
  • 8
  • 16