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.
    class YourSwiftClass : NSObject
  • Declare a class (static) method which returns a new instance of the object:
    class func newInstance() -> YourSwiftClass {
        return YourSwiftClass()
    }
  • Implement the alloc method – similar to the previous solution
    class func alloc() -> YourSwiftClass {
        return YourSwiftClass()
    }
  • Use a kind of introspection
    [[NSClassFromString(@"YourProjectName.YourSwiftClass") alloc] init]
  • Declare but not implement a category in the ObjC code where you want to allocate the Swift object – yes, it really works
    @interface YourSwiftClass (allocation)
        + (instancetype)alloc;
    @end