Dynamically set properties from dictionary <String, Any?> In Swift
I am trying to set some properties in a class based on values ββin a dictionary, currently I am doing this:
let view: UIView = UIView()
if let hidden: Bool = self.props["hidden"] as? Bool {
view.hidden = hidden
}
if let frame: CGRect = self.props["frame"] as? CGRect {
self.uiInstance?.frame = frame
}
if let backgroundColor: UIColor = self.props["backgroundColor"] as? UIColor {
self.uiInstance?.backgroundColor = backgroundColor
}
This is fine with multiple properties, but tiresome when it comes to large quantities. Is it possible to quickly do something like:
var view: UIView = UIView()
let config: Dictionary<String, Any?> = ["frame": CGRectZero, "backgroundColor": UIColor.whiteColor()]
for (key, value) in config {
// view.??? = value
}
I know there can be risks of error if there config
was something in the dictionary that didn't match the attribute of the UIView instance. for example ["text": "this is not going to work"]
. But beyond that, is it possible to dynamically set attributes in the class (for example, you can use some other languages, for example ruby ββsend - http://ruby-doc.org/core-2.1.5/Object.html#method-i -send
source to share
This is possible with the NSKeyValueCoding
setValuesForKeysWithDictionary method , which calls setValue:forKey:
for each key-value pair into a dictionary:
let config: [String : AnyObject] = [
"frame": NSValue(CGRect: CGRectZero),
"hidden" : true,
"backgroundColor": UIColor.whiteColor(),
"autoresizingMask" : UIViewAutoresizing.FlexibleHeight.rawValue
]
self.view.setValuesForKeysWithDictionary(config)
But note that all values ββmust be Objective-C objects, so the frame is wrapped in an object NSValue
. More on structured and scalar support in keyword coding can be found
here .
Some types (eg Bool
, Int
) are automatically connected to NSNumber
, so the value true
for the hidden attribute should not be wrapped. "Parameters", such as UIViewAutoresizing
, must be converted to a base integer value (which is then automatically concatenated to NSNumber
).
source to share