In Objective-C that is easy as pie, just call NSClassFromString(aClassName) and then alloc/init the Class it returns. However, now that Swift is destined to become the lingua franca of iOS I decided to investigate how one might implement these reusable components in Swift. Instantiating classes by name turned out to be a stumbling block, as it appears that Swift does not yet support this.
I was able to get an object that represents a class (named AnyClass), but there was no way to get from there to a live instance of that class. So instead, I hopped into the parallel universe of Objective-C to create an object, which then gets returned back to Swift. This is why ObjectFactory can only work with NSObject subclasses; I’m relying on Objective-C to alloc/init a new object, and those methods are defined by NSObject.
I still think one of the less remarked on aspects of Swift is its lack of dynamism. It does not seem like Core Data, Scripting Bridge, or PyObjC could be written in Swift. Swift gives you a smarter compiler, but less flexibility at runtime. Swift is famously advertised as Objective-C without the C. Curt Clifton says:
Starting to fear that Swift is really Obj-C without the Smalltalk[…]
Stay up-to-date by subscribing to the Comments RSS Feed for this post.