Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 618
Hasan Akgün Avatar asked Jan 13 '15 17:01

Hasan Akgün


People also ask

How do you print a variable in Swift?

In Swift, you can print a variable or a constant to the screen using the print() function.

When to use struct vs class Swift?

When choosing between structs and classes, it's important to remember the key differences: Classes are reference types, and structs are value types. If class inheritance is not needed, structs are faster and more memory efficient. Use structs for unique copies of an object with independent states.

How to define class in Swift?

Classes in Swift are similar to Structures in Swift. These are building blocks of flexible constructs. You can define class properties and methods like constants, variables and functions are defined. In Swift 4, you don't need to create interfaces or implementation files while declaring classes.


2 Answers

How you can do it in Swift 3.0 recursively:

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()

results:

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
like image 54
Integer Avatar answered Oct 15 '22 22:10

Integer


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]
like image 41
Jason W Avatar answered Oct 15 '22 22:10

Jason W