Can I set values ​​for the properties of a Swift object using mirroring?

At the moment, I can check object variables using the Mirror type. But can I set values ​​for my variables using mirroring? Or maybe there is another clean-fast way?

For example, I would like to create an object (Swift struct ) from JSON. Is this possible without subclassing NSObject and using Objective-C functions for this?

+6
source share
2 answers

That was the best I can do at the moment. There is still no conversion of mirrorObject back to its generic type. FYI uses SwiftyJSON

 func convertToObject<T>(json: JSON, genericObject: T) -> T { let mirroredObject = Mirror(reflecting: genericObject) for (_, var attr) in mirroredObject.children.enumerate() { if let propertyName = attr.label as String! { attr.value = json[propertyName] print(propertyName) print(attr.value) } } // Figure out how to convert back to object type... } 
+2
source

This is an old question, but the answer did not work for me.

I had to change my quick object to NSObject in order for everything to work, as well as have dynamic properties.

In my case, I use pod marshal to deserialize the data.

  class MyClass: NSObject, Unmarshaling { // @objc dynamic make property available for NSObject @objc dynamic var myProperty: String? required init(object: MarshaledObject) throws { super.init() initUsingReflection(object: object) } func initUsingReflection(object: MarshaledObject) { let mirror = Mirror(reflecting: self) // we go through children for child in mirror.children { guard let key = child.label else { continue } // This line is here to get the value from json, in my case I already know the type I needed let myValue: String = try! object.value(for: key) // The trick is here, setValue only exist in NSObject and not in swift object. self.setValue(myValue, forKey: key) } } } 
0
source

All Articles