Allocate Swift objects from Objective-C


Using mixed projects you can face with several challenging situations. One of them is the allocation of Swift objects in ObjC code.

The general problem that Swift objects doesn’t have an alloc method which is used to allocate the memory in ObjC ([[SwiftClass alloc] init]).
To access the Swift object you should prefix it with @objc – or subclass from NSObject.

There are several workarounds however:

  • Make the NSObject as base class of the Swift class. As you use mixed project already this seems to be the best solution.
  • Declare a class (static) method which returns a new instance of the object:
  • Implement the alloc method – similar to the previous solution
  • Use a kind of introspection
  • Declare but not implement a category in the ObjC code where you want to allocate the Swift object – yes, it really works