Use Swift Class in Objective C

Sometimes we would like to include the Code written in the Swift Language to be used in Objective-C file.

Recently, I ran into a situation where I need to use my Swift written code into Objective-C .m file.

Before we start this, we need to understand @objc . It's an attribute which helps the swift code interoperability with Objective-C code.

Consider the below code:

class User : NSObject {
    init(_ nameId: Int) { }
    init(_ name: String) { }

}


Here, the 'User' can be initialized by nameId or name, but Objective-C does not understand this short hand implementation. It would not know which initialization to call , one with nameId or one with just name.

class User : NSObject {
    @objc(initWithNameID:) init(_ nameId: Int) { }
    @objc(initWithName:) init(_ name: String) { }

}

The Objective-c code will now know there are two initialization methods, one initWithNameID  and  initWithName.

@objc(initWithNameID:) means this method in Objective-C will be called as initWithNameID: , consider it as 'alias name' for simple understanding.

So should we think after this we have achieved our goal. Most probably yes.!!!!!!!!

There is one setting that you should check in Settings:
In Build Settings , check the setting name "SWIFT_OBJC_INTERFACE_HEADER_NAME".  The swift compiler has a job to create this header file.

You don't have to worry on creating this header file, it's an Xcode-generated file.

The value would be "ProductModuleName-Swift.h".

So, far we have done a good job and the final part is to just import the mentioned header file , with '-Swift' prefix.

#import "Employee.h"
#import "MyProject-Swift.h"

@implementation Employee

-(void)callMethod{
    
    [[User alloc] initWithName:@"Ray"];
}


@end


This is how we can use Swift Code in Objective-C. :)

Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

How to set Custom Section Header in UITableView for ios sdk version greater than 6