2017-10-10 57 views
0
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]。我如何獲得Swift 4中的類屬性列表?

+1

見https://stackoverflow.com/q/44762460/1187415和https://stackoverflow.com/q/44390378/1187415:你必須明確地在Swift 4中使用'@ objc'將成員暴露給Objective-C運行時。 –

+0

[swift中類的屬性列表]的可能重複(https://stackoverflow.com/questions/24844681/list-of-classs-properties-在-SWIFT) – Ibo

回答

0

你可以得到'的屬性,如下面:

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