Friday, June 13, 2014

Instantiating Classes by Name in Swift

Josh Smith:

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[…]

5 Comments RSS · Twitter

I should note that both Josh and Matt’s examples are about how to use the Objective-C runtime to instantiate Objective-C-compatible classes from Swift. This won’t work for pure Swift classes.

[...] Owens II has some criticisms along this line that differ from those I mentioned before (via Christoffer [...]

[...] without the C”, but in many ways, Swift is closer to “C++ without the C” (or Objective-C without the Smalltalk). Swift’s generics, for example, are closer to C++’s templates than to any feature of [...]

[…] Good Thing and a Step Back. There’s much to like about Swift, but much has been lost as well: instantiating classes by name, the ability to write your own Core Data–like framework, message passing (contra vtable […]

Leave a Comment