7

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.

Patru
  • 4,481
  • 2
  • 32
  • 42
steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • Swift's reflect function seems to only allow reading properties (at least as of beta 7). This post: http://stackoverflow.com/questions/24245262/qa-call-a-method-from-a-string-in-swift combined with a setter method might give you what you need. – Eran Globen Sep 10 '14 at 23:37
  • @EranGloben Good thought. That would work, but I'd need to be guaranteed there was a setter method for each and every property, and since I don't see any way to reflect on methods in swift, I can't guarantee myself that.... ideas on that front? I feel I may just be out of luck. – steventnorris Sep 11 '14 at 18:56
  • Have you found here a solution for that ? – Konstantin Heinrich Jun 16 '15 at 14:51
  • @KonstantinHeinrich I have not. As it seems, there is no swift way to do this. I did find some highly complicated C work that someone tried with mixed results they were able to shoe-horn into Swift, but I'm not convinced it's the best route. It may be the only route, however. – steventnorris Jun 16 '15 at 15:29
  • @steventnorris Ok, i have researched some sites but also didn´t found somethink useful. Does Swift has an class like in C# "Type" or "PropertyInfo"? It is very anoying that you can not set new property values :-( – Konstantin Heinrich Jun 16 '15 at 16:13
  • @KonstantinHeinrich Nothing reliable that I've found. The reflection abilities of Swift seem severely lacking. There seems to be some beginning to it, although I haven't tried this myself yet. http://stackoverflow.com/questions/24060667/does-swift-support-reflection – steventnorris Jun 16 '15 at 16:27

1 Answers1

1

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

Edwin Vermeer
  • 13,017
  • 2
  • 34
  • 58