Reputation: 2070
I know a few questions already exist that seem to kinda cover what I'm asking (such as Dynamically set properties from Dictionary<String, Any?> in Swift), but this doesn't seem to be quite what I'm looking for.
Basically, I have a base object where I want to set the properties based on an object, like so:
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 of keys/values and have them be dynamically added as properties of the object. I know that this behavior is possible in PHP, for example by doing $this->{$key} = $value
, but I am somewhat unfamiliar with Swift so I haven't been able to figure out how to do this yet.
Also, if anybody could tell me the name of the functionality I'm trying to achieve here, that'd be really helpful. Not knowing what this concept is called is making searching for answers difficult :c
Upvotes: 4
Views: 4714
Reputation: 21154
I want to expand on the example given by @Okapi. If your class is a subclass of NSObject, then the setValue:forKey: and valueForKey: method are present by default. So, you could 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)
}
}
}
Upvotes: 11
Reputation:
In your object define (or override) setValue:forKey:
, then call this from you init method like so:
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
}
}
}
Upvotes: 1