Wednesday, 30 January 2019

Using Swift and Objective-C together


Normally, when we are going to add new features written in Swift or doing refactoring work in Objective-C code base, we want to be able to use Swift code in Objective-C. And we will probably need to use old Objective-C code in Swift.

When creating a Swift file for the first time, XCode will prompt to generate Bridging header file. ProjectName-Swift.h will be generated at the same time. 

Use Swift in Objective-C:

Import "ProjectName-Swift.h" file in you Objective-C code which XCode created and configure in BuildingSettings automatically for you.

In order to access the Swift classes, properties and functions, @objc modifier needs to be added before declaration of the class/function/property. Also the Swift class has to subclass NSObject.

Use Objective-c in Swift:

When trying to add new .m file, Xcode will prompt to create a bridging header file named ProjectName-Bridging-Header.h which will be automatically added in Build Settings for the target. Also we can create the header file by ourself and added in Building Settings manually, but the name must be ProjectName-Bridging-Header.h. Next, import File.h or any old .h files in the bridging file. Now you will be able to use Objectivce-C class.

Limitations when using Swift and Objective-C together:

It's not possible to use everything in Swift,  you may get compile errors when try to expose Swift code for the following examples:






No comments:

Post a Comment