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

Swift Get all the properties in generic class

我正在尝试获取通用 class T 的所有成员,我可以获取基于特定 classproperties。 但是,我如何使用 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)")
  }
}

我将其添加为扩展

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
    }
}