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 found here. But in spite of it I would like to share my experience on real examples, because it’s not so simple as it says.
Let’s start from Obj 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:
// // SwiftController.swift // ios_objc_mix // // Created by Maxim Bilan on 1/17/15. // Copyright (c) 2015 Maxim Bilan. All rights reserved. // import UIKit @objc class SwiftController: UIViewController { }
2. Defines module set to ‘YES’:
![alt tag](https://raw.github.com/maximbilan/ios_swift_objc_mix/master/img/4.png)
3. Embedded Content Contains Swift set to ‘YES’:
![alt tag](https://raw.github.com/maximbilan/ios_swift_objc_mix/master/img/5.png)
4. After that you should found the Product Module Name in your target settings:
![alt tag](https://raw.github.com/maximbilan/ios_swift_objc_mix/master/img/6.png)
5. And please include a header for Swift compatibility for example to a pch file.
#import “Product Module Name-Swift.h”
// // ios_objc_mix-PrefixHeader.pch // ios_objc_mix // // Created by Maxim Bilan on 1/17/15. // Copyright (c) 2015 Maxim Bilan. All rights reserved. // #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 set up the module.
It’s a similar process. And simpler.
Add Obj C file to project.
And also please choose ‘YES’:
Include our Obj C View Controller to bridging header:
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import "ObjCViewController.h"
And that’s all.
You also you can find example on github.
Hopefully this will save time for someone. Don’t forget star the github repository ☺