Madhav Sharma Madhav Sharma - 1 year ago 64
Objective-C Question

What effect does Swift's lack of dynamic capabilities have when developing?

I am CS student relatively new to Cocoa/CocoaTouch and I am trying to understand the nature of OS X/iOS dev. I understand the difference between dynamic and static languages.

Static languages have all variables bound to a type etc. Variables are bound during execution for dynamic etc.

However, when I am developing OS X apps I struggle to see the examples where dynamic functionality would change things? Can someone explain what someone explain what Obj-C can support that Swift fundamentally cannot when developing apps?
I have come across many cases where the lack of flexibility has forced me to refactor my code, but that's not what I am talking about, or am I confused?

Answer Source

Can someone explain what someone explain what Obj-C can support that Swift fundamentally cannot when developing apps

What I used to take advantage of in Objective-C was not so much dynamic typing as dynamic messaging. The whole messaging apparatus can be rejiggered at runtime, from simple key-value coding or performSelector to dynamic injection of methods into a class at runtime, method swizzling, and key-value observing.

You can do all those things in Swift, but only provided you are talking to Objective-C (i.e. this is an NSObject). That's because all of those things are actually done in Objective-C. You could not, for example, implement even the most basic key-value coding in pure Swift, in the absence of Foundation, as Swift has neither dynamic messaging nor true introspection.

From the point of view of practical app programming, however, I don't miss any of that. For one thing, I am always talking to Objective-C, because Cocoa is in Objective-C. For another thing, it turns out that most of these tricks weren't really necessary, and I've mostly found other ways to accomplish my practical goals. I do still use some key-value coding (especially to do tricks like store an arbitrary value inside a CALayer), but on the whole I've cut way back on my use of such stuff, mostly thanks to the fact that functions are first-class citizens in Swift.

As for dynamic typing, I don't miss it for an instant; changing to Swift has actually saved me from mistakes that I was making without even realizing it because of dynamic typing imposed on me by the APIs (e.g. the fact that objectAtIndex: returned an id — though, to be sure, this is less likely to trouble you today thanks to "lightweight generics").

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download