Fast dynamic property setting based on array keys

I know of a few pre-existing questions that seem curious to cover what I'm asking (e.g. Dynamically setting properties from a <String, Any?> Dictionary in Swift ), but that doesn't sound like what I'm looking for.

Basically, I have a base object where I want to set properties based on the object, for example:

init(data: Dictionary<String,String>)
{

    for (key, value) in data
    {
        //TODO set property as value here?
    }
}

      

I want to be able to pass a dictionary in keys / values ​​and add them dynamically as properties of an object. I know this behavior is possible in PHP, for example by doing $this->{$key} = $value

, but I'm a bit unfamiliar with Swift so I haven't been able to figure out how to do this yet.

Also, if anyone can tell me the name of the function I am trying to achieve here, that would be very helpful. Not knowing what is called this concept makes it difficult to find answers: c

+3


source to share


2 answers


I want to expand on the example given by @Okapi. If your class is a subclass of NSObject , then the setValue: forKey: and valueForKey: methods are present by default . Thus, you can simply set your properties using the following code,



class Foo: NSObject {
    var x:String=""
    var y:String=""
    var z:String=""
    init(data: Dictionary<String,String>) {
        super.init()
        for (key,value) in data {
            self.setValue(value, forKey: key)
        }
    }
}

      

+10


source


In a define object (or override) setValue:forKey:

, then call it from the init method like this:

class Foo {
var x:String=""
var y:String=""
var z:String=""
init(data: Dictionary<String,String>) {
    for (key,value) in data {
        self.setValue(value, forKey: key)
    }
}
func setValue(value: AnyObject?, forKey key: String) {
    switch key {
    case "x" where value is String:
        self.x=value as String
    case "y" where value is String:
        self.y=value as String
    case "z" where value is String:
        self.z=value as String
    default:
        //super.setValue(value, forKey: key)
        return
    }
}

      



}

0


source







All Articles