Parv Bhasker
Parv Bhasker

Reputation: 1901

Is it possible to use dynamic variable for a class member variable

I have a class like

class Person {
   var address:String
   var number:String
   var houseNo:String
   var licenceNo:String
   ....
}


let jone = Person()
    jone.number = "123456"

So in this i need to initialize the variable of person class one by one. And i have approx 30 variables in person class.

Is not there s simple way to do this ?

like I have all the keys coming from backend like "number = 123456". Is not there a way that i run a for loop and use something like.

for key in keys {
   john."\(key)" = dict[key]
}

Is not there a way to shorten this lengthy procedure ?

Upvotes: 0

Views: 134

Answers (2)

AshvinGudaliya
AshvinGudaliya

Reputation: 3314

You can try out this code

extension NSObject{
    // fetch all class varible
    func property() -> Mirror.Children {
        return Mirror(reflecting: self).children
    }

    func propertyList() {

        for (name, value) in property() {
            guard let name = name else { continue }
            print("\(name): \(type(of: value)) = '\(value)'")
        }
    }
}

Your class, set value like below code it's helpfull

class Person: NSObject {
    var address:String = ""
    var number:String = ""
    var houseNo:String = ""
    var licenceNo:String = ""

    init(with response: [String: AnyObject]) {
        for child in self.property() {

            if let key = child.label, let value = response[key] {
                self.setValue(value, forKey: key)
            }
        }
    }
}

person.propertyList()

// Display all class property list
address: String = ''
number: String = ''
houseNo: String = ''
licenceNo: String = ''

Upvotes: 1

fenix
fenix

Reputation: 53

Why don't use a Person method for load the backend response into a new Person object?

Somethind like that:

let jone = Person()
jone.loadDataFrom(response)

Or use a Person static method

let jone = Person.loadDataFrom(response)

static func loadDataFrom(response:Object) -> Person {
    let p = Person()
    ...
    set response data
    ...

    return p

}

Upvotes: 0

Related Questions