Swift获取泛型类中的所有属性

时间:2018-04-05 23:44:34

标签: swift mirror

我正在尝试获取通用类T的所有成员,我可以根据特定的properties获取class。 但是,我如何使用Mirror

来做到这一点
let mirrored_object = Mirror(reflecting: user)

for (index, attr) in mirrored_object.children.enumerated() {
  if let propertyName = attr.label as String! {
    print("Attr \(index): \(propertyName) = \(attr.value)")
  }
}

1 个答案:

答案 0 :(得分:0)

我将其添加为扩展程序

extension NSObject {
    public func GetAsJson() -> [[String:Any?]] {
        var result:[[String: Any?]] = [[String: Any?]]()

        for item in self {
            var dict: [String: Any?] = [:]
            for property in Mirror(reflecting: self).children {
                dict[property.label!] = property.value
            }
            result.append(dict)
        }
        return result
    }
}