如何在swift中列出类的所有变量

Has*_*gün 11 variables class swift

有没有办法在Swift中列出类的所有变量?

例如:

class foo {
   var a:Int? = 1
   var b:String? = "John"
}
Run Code Online (Sandbox Code Playgroud)

我想这样列出: [a:1, b:"John"]

Int*_*ger 16

如何以递归方式在Swift 3.0中执行此操作:

import Foundation

class FirstClass {
    var name = ""
    var last_name = ""
    var age = 0
    var other = "abc"

    func listPropertiesWithValues(reflect: Mirror? = nil) {
        let mirror = reflect ?? Mirror(reflecting: self)
        if mirror.superclassMirror != nil {
            self.listPropertiesWithValues(reflect: mirror.superclassMirror)
        }

        for (index, attr) in mirror.children.enumerated() {
            if let property_name = attr.label {
                //You can represent the results however you want here!!!
                print("\(mirror.description) \(index): \(property_name) = \(attr.value)")
            }
        }
    }

}


class SecondClass: FirstClass {
    var yetAnother = "YetAnother"
}

var second = SecondClass()
second.name  = "Name"
second.last_name = "Last Name"
second.age = 20

second.listPropertiesWithValues()
Run Code Online (Sandbox Code Playgroud)

结果:

Mirror for FirstClass 0: name = Name
Mirror for FirstClass 1: last_name = Last Name
Mirror for FirstClass 2: age = 20
Mirror for FirstClass 3: other = abc
Mirror for SecondClass 0: yetAnother = YetAnother
Run Code Online (Sandbox Code Playgroud)


Jas*_*n W 8

以下内容应使用反射来生成成员和值列表.请参阅http://swiftstub.com/836291913/

class foo {
   var a:Int? = 1
   var b:String? = "John"
}
let obj = foo()
let reflected = reflect(obj)
var members = [String: String]()
for index in 0..<reflected.count {
    members[reflected[index].0] = reflected[index].1.summary
}
println(members)
Run Code Online (Sandbox Code Playgroud)

输出:

[b: John, a: 1]
Run Code Online (Sandbox Code Playgroud)