Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reflection to Change Properties in Swift

I am attempting to create a serializer that will change the properties of an object.

Example:

class testobj{
    var prop1:Int = 3
    var prop2:String = "Hello"
    var prop3:Dictionary<String,String> = Dictionary<String,String>()
}

I know I can access the names and types of the properties using

reflect(testobjc())[0].1

and

var tester = testobj()
_std_lib_DemangledTypeName(tester.prop1)

but what I would like to do is something like

var tester = testobj()
for(var x:Int = 0; x < reflect(testobj()).count; x++){
    if(_std_lib_DemangledTypeName(tester.(reflect(testobj())[0].1)) == "Swift.String"){
        tester.(reflect(testobj())[0].1) = "World!"
    }
}

Essentially, I want to loop through all the properties listed for a given class and set the properties on a newly created object of that class. Any guidance would be appreciated. Swift reflection is new to me.

like image 711
steventnorris Avatar asked Sep 10 '14 20:09

steventnorris


1 Answers

You could use this class to create a dictionary form an object and an object from a dictionary. https://github.com/evermeer/EVReflection

like image 187
Edwin Vermeer Avatar answered Dec 02 '22 07:12

Edwin Vermeer