How can I import Swift code to Objective-C? How can I import Swift code to Objective-C? objective-c objective-c

How can I import Swift code to Objective-C?


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 becomes My_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


Here's what to do:

  1. Create a new Project in Objective-C

  2. Create a new .swift file  

    • A popup window will appear and ask "Would You like to configure an Objective-C bridging Header".
    • Choose Yes.
  3. Click on your Xcode Project file

  4. Click on Build Settings

  5. Find the Search bar and search for Defines Module.

  6. Change value to Yes.

  7. Search Product Module Name.

  8. Change the value to the name of your project.

  9. 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"


Instructions from the Apple website:

To import Swift code into Objective-C from the same framework

Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .m file within that framework target using this syntax and substituting the appropriate names:

#import "ProductName-Swift.h"

Revision:

You can only import "ProductName-Swift.h" in .m files.

The Swift files in your target will be visible in Objective-C .m files containing this import statement.

To avoid cyclical references, don’t import Swift into an Objective-C header file. Instead, you can forward declare a Swift class to use it in an Objective-C header. Note that you cannot subclass a Swift class in Objective-C.

enter image description here