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.
- Implement you Swift class with
@objc
attribute:@import UIKit @objc class SwiftController: UIViewController { }
- Defines module set to Yes:
- Embedded Content Contains Swift set to Yes:
- After that you should found the Product Module Name in your target settings:
- 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> #endif #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.