How can I import Swift code to Objective-C?
Here's what to do:
Create a new Project in Objective-C
Create a new
.swift
file- A popup window will appear and ask "Would You like to configure an Objective-C bridging Header".
- Choose Yes.
Click on your Xcode Project file
Click on Build Settings
Find the Search bar and search for Defines Module.
Change value to Yes.
Search Product Module Name.
Change the value to the name of your project.
In App delegate, add the following :
#import "YourProjectName-Swift.h"
Note: Whenever you want to use your Swift file you must be import following line :
#import "YourProjectName-Swift.h"
You need to import ProductName-Swift.h
. Note that it's the product name - the other answers make the mistake of using the class name.
This single file is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc
or inherit from NSObject
.
Considerations:
If your product name contains spaces, replace them with underscores (e.g.
My Project
becomesMy_Project-Swift.h
)If your target is a framework, you need to import
<ProductName/ProductName-Swift.h>
Make sure your Swift file is member of the target