Objective-C meets Swift
On a grey Autumn morning, when the coffee is yet to hit the spot, it can sometimes feel like Objective-C code is Shakespearean English and Swift is the latest London Cockney slang.
For sure there are some similarities but converting or translating from one to the other can be one big head ache. Should we just sling Macbeth and his Objective-C into the trash and start afresh with the new hipster Swift, or is a sensible migration possible?
How to use Objective-C code in a Swift project
Sometimes you may find that you need a no longer updated Objective-C library in your Swift project. Ideally you’d migrate this code to Swift, but what if the code is quite complex or requires a lot of time to migrate it? In that case you may need to still use that code in Objective-C.
Fortunately this is possible with Swift. You can mix Swift and Objective-C file in the same project. I’ll show you how to do this with an example: I need a cypher library that was written in Objective-C and I haven’t found anything similar in Swift. If I want to use that library I need to use that Objective-C library.
Some simple steps to follow
Follow these steps to set it up:
1. Open your Swift project in Xcode or create it.
2. Add the desired Objective-C files to this project. Xcode normally suggests you configure a bridging header to link these files. Click yes and a header file will be created. The name of this file isn’t important, but I suggest you use the following syntax: YOUR_PROJECT_NAME-Bridging-Header.h. Just in case Xcode didn’t suggest it, create an Objective-C header file and set the recommended format.
3. Select your project file and open the build settings tab. Ensure that your header file was set in the Objective-C bridging header section. Otherwise set it manually specifying the project name before.
4. Open the header file and import all the required Objective-C header files that Swift will need to use the Objective-C code.
5. Call the Objective-C method like a Swift function e.g:
That's it. Simple huh? You can test the results on your own by checking the full source code on our Github account. Happy coding!
This article was originally written for Brightec by Jose Martinez