4

As an experienced Objective-C developer who is now learning Swift , I'm really missing some of the reflection and dynamic features of Objective-C.

For eg: I had written a JSON serializer which automatically mapped keys and values using KVO and Objective C introspection , and there are open source libraries like Mantle which do this.

I could declare my object as an NSObject subclass and proceed but I feel that this is not the Swift way of doing things.

Is there any other way to accomplish the same tasks , while avoiding boilerplate , using what Swift provides ?

coderboy
  • 193
  • 5

1 Answers1

3

EDIT: (2016) this answer is auto-dated. Some of the advice may still be relevant but now that Swift is open-source, I would look into other possible answers.

There is no native KVO reflection like what you described built into Swift. See: https://stackoverflow.com/a/24092370/798682

And based on what we do know about how the Swift compiler optimizes method execution at compile time (vs the pure runtime implementation of ObjC) it doesn’t seem likely to be added anytime soon. See https://stackoverflow.com/a/25438299/798682 and http://blog.untitledkingdom.co.uk/obj-c-vs-swift/ for more info on that.

With all that being said, here is a blog post on some KVO alternatives in Swift: http://blog.scottlogic.com/2015/02/11/swift-kvo-alternatives.html and another that details some of the reflection capabilities that are in Swift: http://freecake.angelodipaolo.org/simple-reflection-in-swift/.

Community
  • 1
  • 1
mattr
  • 5,458
  • 2
  • 27
  • 22
  • The blog posts talk about KVO .. but I'm talking about KVC Key value coding and run time introspection. – coderboy Aug 04 '15 at 16:57
  • Gotcha. Yeah I was mostly saying that there isn't much in Swift and offering what is there. Hopefully that will change soon. Good luck! – mattr Aug 04 '15 at 17:18
  • Yeah I appreciate that. I upvoted you but I'm hoping someone creative might be able to come up with something a bit more workable. – coderboy Aug 18 '15 at 14:42