Hasan Akgün Hasan Akgün - 24 days ago 10
Swift Question

How to list all Variables of a class in swift

Is there a way to list all Variables of a class in Swift?

For example:

class foo {
var a:Int? = 1
var b:String? = "John"
}


I want to list it like this:
[a:1, b:"John"]

Answer

The following should use reflection to generate the list of members and values. See fiddle at 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)

Output:

[b: John, a: 1]