April 22, 2015

Mixing Swift And Objective C Code In The Same Project

Yes, there is opportunity to combine this languages in the same project. It’s great. Apple provides a tutorial how to do this magic. You can find here. But in spite of it I would like to share my experience on real examples, because it’s not as simple as it sounds.

Swift code in Objective C project

Let’s start from Objective C project, and will try to add Swift code to this project. Create the Obj C project. And create new Swift class.

For example, UIViewController:

After that, you will see the following popup message:

Please, choose Yes.

Now, you have ios_objc_mix-Bridging-Header.h file. In this header you can import source files for your Swift class.

After that, you can do the next steps.

  1. Implement you Swift class with @objc attribute:
    @import UIKit
    @objc class SwiftController: UIViewController {
  2. Defines module set to Yes:

  3. Embedded Content Contains Swift set to Yes:

  4. After that you should found the Product Module Name in your target settings:

  5. And please include header for Swift compatibility for example to pch file.
    #import “Product Module Name-Swift.h”
    #ifdef __OBJC__
        #import <UIKit/UIKit.h>
        #import <Foundation/Foundation.h>
    #import "ios_objc_mix-Swift.h"

And now you can use Swift code. Please, see the example on github.

Note: ios_objc_mix-Swift.h file you can’t find in your project browser Xcode automatically generates this header. Magic!

Note: if you have a lot of targets in your project. It really is a pain. You should import magic Product-module-name-Swift.h headers for each target.

Note: if you use Swift classes in the Interface Builder, you should setup the module.

Obj C code in Swift project

It’s similar process. And simpler.

Add Obj C file to project.

And also please choose Yes:

Include our Obj C View Controller to bridging header:

#import "ObjCViewController.h"

And that’s all.

You also you can found example on github.

Hopefully this will save time for someone. Don’t forget star the github repository.

We would love to hear from you.

This form sends a email right into our inbox. One of us will get back to you as soon as possible.

Thanks for contacting us!

We will respond as soon as possible - normally, within a day.

Want to get in touch even faster? Then, please, try:

Calling us at +1-424-777-2021.

Skyping factorial.complexity.

Something went wrong :(

We are very sorry. Here are some alternative ways to contact us:

Want to get in touch even faster? Then, please, try:

Phone +1-424-777-2021

Skype factorial.complexity

Email info@f17y.com