Bridging Objective-C and Swift Classes.
Since been announced in WWDC 2014, Swift has been centre of iOS native application development. Yes! Swift is awesome, it comes with awesome features, easy to code and maintain. Definitely Swift facilitated new approaches to software development for the iOS and macOS platforms. Developers are loving it all over the world. But, what about applications already written in Objective-C. Can these developers developing or maintaining apps written in Objective-C take advantages of all these new and powerfull features of Swift.
I will try to answer this question in this blog with pros and cons.
Yes! we can bridge classes written in both the languages together. Classes of Swift can be exposed to Objective-C classes and Vice Versa. Lets see how to do that.
Using Swift classes in Objective-C
If you are adding new modules or screens to your existing application you might think of writing new code in Swift. This will straight lead you to a question How to Bridge Objective-C class to Swift?
This one is easier than you think.
- Create a .swiftfile and add it to your project.
- Write your class
3. In your Objective-C class .mfile add bridging header to import swift class.
#import "<#YourProjectName#>-Swift.h"
4. Swift bridging file will automatically get created in your project. If you click and go to the file , it will show you Objective-C format interfaces for your swift class.
5. Use your class as you would use an Objective-C class. Xcode will even suggest you autocomplete for your swift functions in Objective-C syntax.
Note: Doing a quick build might give you some errors. Dont panic!. Clean build the project and then run.
Using Objective-C classes in Swift
First thing you need is Objective-C bridging header file. You might already have one. If not add a new .h file to your project and name it
"<#YourProjectName#>-Bridging-Header.h"
Now, whichever classes you want to be exposed to swift classes, write their Class header in “<#YourProjectName#>-Bridging-Header.h” class. As #import MyObjCClass.h . This will make your mentioned class exposed to all swift classes in your project. Now you can create object or call functions of Objective-C class from swift class.
See Apple Guide https://developer.apple.com/documentation/swift#2984801
There are few problems and challanges too with interfacing classes written in Objective-C and swift. I will cover these in a separate article. Also please feel free to give your thoughts and advices. Thank You 😊.