Swift and Objective-C

How To Use Both Swift And Objective-C In One Project?

The Swift and Objective-C interoperability is very good so that it is very easy to use both Swift and Objective-C in one project.

Using Objective-C code in Swift files

In the so-called bridging-header file you can import Objective-C files. Xcode translates then all signatures to Swift, so that it feels like you are calling real Swift functions.

The easiest way to create the bridging-header file is by creating a new Objective-C class. If there is no bridging-header file in your project yet, Xcode asks you if the bridging-header file should be created. You can also manually create it: Just create an Objective-C header file, for example “Bridging-Header.h”.  Then go to the “Swift Compiler – Code generation” section in the build settings and set the name of the bridging-header file in the field “Objective-C Bridging Header”.

After adding an Objective-C file to the bridging header file, you should compile the project first before trying to access the translated signatures.

Using Swift code in Objective-C files

The other way round is even easier. Xcode automatically creates a file that contains the translated signatures. You just have to important a file called “<ProductModuleName>-Swift.h” into the Objective-C files:

The product module name is just the name of the project. All Swift classes that inherits from NSObject  – or from on of its subclasses – are available then in the Objective-C file.

Again, you should compile your project before trying to access the translated signatures.

 Why should you use both Swift and Objective-C in one project?

So one questions remains: Why should you even use both Objective-C and Swift in one project? Well, if you are starting a new project it’s a good idea to use Swift. But you want to use for sure some libraries or old code. And if they are written in Objective-C, you can easily use them.  Conversely, you could also use Swift in an Objective-C project. This way you can slowly start to learn Swift. There are some posts about that topic on this blog:

References

@ Anchiy / shutterstock.com
iBook Store: Using Swift with Cocoa and Objective-C

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon