How can I import Swift code to Objective-C?

229,867

Solution 1

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

Solution 2

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"

Solution 3

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

Solution 4

If you're using Cocoapods and trying to use a Swift pod in an ObjC project you can simply do the following:

@import <FrameworkName>;

enter image description here

Solution 5

Go to build settings in your project file and search for "Objective-C Generated Interface Header Name. The value of that property is the name that you should include.

If your "Product Module Name" property (the one that the above property depends on by default) varies depending on whether you compile for test/debug/release/etc (like it does in my case), then make this property independent of that variation by setting a custom name.

Share:
229,867

Related videos on Youtube

Dark Matter
Author by

Dark Matter

Updated on July 08, 2022

Comments

  • Dark Matter
    Dark Matter almost 2 years

    I have written a library in Swift and I wasn't able to import it to my current project, written in Objective-C.

    Are there any ways to import it?

    #import "SCLAlertView.swift" - 'SCLAlertView.swift' file not found
    
    • SleepsOnNewspapers
      SleepsOnNewspapers about 9 years
      love this project!
    • Vin
      Vin over 3 years
      Answer to this question can be found in the Apple documentation itself: developer.apple.com/documentation/swift/… I recommend to read the documentation first before reading all the answers.
  • Dark Matter
    Dark Matter almost 10 years
    Showed me this error: 'SCLAlertView-Swift.h' file not found.
  • Bill
    Bill almost 10 years
    Needs to be the project name, not the filename - see my answer.
  • louielouie
    louielouie almost 10 years
    Thanks for the documentation link. That was useful for reference.
  • louielouie
    louielouie almost 10 years
    Note that if you try to use the Swift filename in your import, you will get the error "Expected ';' after top level declarator". in your Swift file after "import Foundation".
  • Ruben Martinez Jr.
    Ruben Martinez Jr. almost 10 years
    Wow, great catch! Small question: Is there anywhere I can see what that project name is? I tried what you suggested and am still getting errors so I'm worried I might have the project name wrong.
  • Ruben Martinez Jr.
    Ruben Martinez Jr. almost 10 years
    EDIT: Note: for this to work, a project module name MUST be defined. See: stackoverflow.com/a/24064015/2085743
  • Hola Soy Edu Feliz Navidad
    Hola Soy Edu Feliz Navidad over 9 years
    I just would like to add a note that if your project name has any white space or special character you have to replace them with underscores, like "My App" would be "My_App-Swift.h"
  • Chris
    Chris almost 9 years
    To quote from the provided link: The name of this header is your product module name followed by adding "-Swift.h". So it's not the class name as you wrote, but the name of your product module and that takes care of importing all swift files, not just a specific one
  • Alphonse R. Dsouza
    Alphonse R. Dsouza almost 9 years
    Only import "ProductName-Swift.h" in .m files helped me. Adding same in .pch file was giving "Cannot find protocol declaration for 'CLLocationManagerDelegate'; did you mean 'NSLayoutManagerDelegate'?"
  • Hardik Amal
    Hardik Amal over 8 years
    Hi @Bill how do i use swift library through cocoapod in my objective c project...?
  • marchinram
    marchinram over 8 years
    How does this work in a Framework target, can you just add #import <ProjectName/ProjectName-Swift.h> to the umbrella header?
  • uchuugaka
    uchuugaka over 8 years
    Why is this so hard and poorly documented?
  • Raptor
    Raptor over 8 years
    @HardikAmal you can still use, for example, #import "SCLAlertView-Swift.h" in Objective-C class, or @import <SCLAlertView>;
  • Zack Braksa
    Zack Braksa over 8 years
    Changing the value of Defines module in Build settings to Yes is what fixed things for me!
  • Alejandro Iván
    Alejandro Iván over 8 years
    @AJit it doesn't directly, the documentation says that. The easiest way is to create an Objective-C class that translates in a format that Objective-C++ understands. developer.apple.com/library/ios/documentation/Swift/Conceptu‌​al/…
  • Mohit
    Mohit about 8 years
    Embedded Content Contains Swift : YES USE this also
  • Amit Saxena
    Amit Saxena almost 8 years
    @uchuugaka it's not that much hard. First time you can feel a bit pain and then later you would be getting mastery on it.
  • Sam B
    Sam B almost 8 years
    good answer but steps 7-8 are not needed in Xcode 7.3.1 and higher
  • Maria
    Maria over 7 years
    Thanks! That really helps!
  • itscoderslife
    itscoderslife over 7 years
    Worked for me! Thanks.
  • David T.
    David T. over 7 years
    Note that you have to derive from NSObject !!! you can't just straight up declare a class Blah in swift and have it work. it needs to be class Blah : NSObject
  • inigo333
    inigo333 about 7 years
    Worth reading this answer for some cases: stackoverflow.com/questions/26328034/… Depending on what you are doing: #import <ProductName/ProductModuleName-Swift.h> #import <ProductModuleName-Swift.h> #import <NewTestApp/NewTestApp-Swift.h>
  • Aamir
    Aamir about 7 years
    I have used #import "SCLAlertView-Swift.h" in .m and I getting error: SCLAlertView-Swift.h not found, I did something wrong?
  • Aamir
    Aamir about 7 years
    @Bill now I have used #import "Wow_Dictionary-Swift.h", where Wow Dictionary is my project name. Now I am getting error Wow_Dictionary-Swift.h not found. Still something wrong?
  • Bill
    Bill about 7 years
    @Aamir Actually, it's the target name, not the project name. Let me update my answer.
  • Aamir
    Aamir about 7 years
    @Bill my project name is same as target name.
  • Philipp Otto
    Philipp Otto almost 7 years
    The forward declaration (@class) of the class is a very good point! Thanks!
  • Jaydeep Vyas
    Jaydeep Vyas almost 7 years
    I have skipped step NO. 6 even it is working for me... is this step really needed.??? my define module is set to NO
  • fnc12
    fnc12 almost 7 years
    I did this but I get 10 compile errors saying that No type or protocol UIApplicationDelegate and similar
  • Ricardo
    Ricardo over 6 years
    What if you want import a Swift extension?
  • jose920405
    jose920405 over 6 years
    In my case "ProductName-Swift.h" works perfect in xcode 7.3 but now works in xcode 8.3.2
  • jose920405
    jose920405 over 6 years
    Not works for me in xcode 8.3.2. Works in previous versions
  • rd_
    rd_ over 6 years
    i am not getting this option of use legacy swift language version
  • Roi Mulia
    Roi Mulia over 6 years
    Better than the approved. The dashes wasted 20 min I'll never get back haha.
  • Esha
    Esha over 6 years
    Thanks a lot! you saved my day.
  • John Franke
    John Franke over 6 years
    Do you have to import it in your .m file?
  • Bill
    Bill over 6 years
    @JohnOttenlips yes
  • Darshan Mothreja
    Darshan Mothreja over 6 years
    @AlejandroIván I have UIView swift class will it work ? I am not able to import swift into objective c
  • Sumit singh
    Sumit singh over 6 years
    @jose920405 let me know what step you are following because the same steps for same Xcode version is working for me.
  • lelelo
    lelelo over 6 years
    This auto-generated file is now called TargetName-Bridging-Header.h though?
  • Bill
    Bill over 6 years
    @lelelo No, that file is the opposite of this one. The bridging header is written by the developer and lets you bring Objective-C and C symbols into your Swift code. The Target-Swift.h file is automatically generated and lets your Objective-C/C code access Swift symbols.
  • Martin-Gilles Lavoie
    Martin-Gilles Lavoie about 6 years
    The missing module was my issue for a test project. Furthermore, if your project name starts with a numerical, (eg, 1234.xcodeproj), it too will replace the first offending character with _, thus your module name will default to "_234" and thus your include will look like "_234-Swift.h".
  • atulkhatri
    atulkhatri about 6 years
    It's not necessarily the Target Name. It is actually Product Module Name which you have defined in Build Settings. You can have a look at the answer by Sumit Singh
  • Adeel Miraj
    Adeel Miraj over 5 years
    @Bill sorry to bother you but I have been trying to import the Swift header file but couldn't succeed. The issue is that I have 2 targets in my project. One of the Objective-C files requires to access the Swift header files of both the targets. How would I go about that?
  • Bill
    Bill over 5 years
    Hi @Adeel You can create a new header file that #import's Target1-Swift.h and Target2-Swift.h and import that header into your Objective-C files.
  • Adeel Miraj
    Adeel Miraj over 5 years
    In the newly created header file it doesn't let me include either of the two. Moreover, if I exclude the objective-c file from one of the targets then the compiler stops complaining about the header file but starts complaining about one of objc class's subclass because that is included in both the targets.
  • Tamás Sengel
    Tamás Sengel over 5 years
    "Note that you cannot subclass a Swift class in Objective-C." Thank you for including this, it saved me from going crazy.
  • NSPratik
    NSPratik over 5 years
    This works like a charm if we installed swift-made library through Cocoapods. Upvoted !!!
  • Itachi
    Itachi over 5 years
    I found a new way to find the correct generated header file name: go to your target -> Build Settings -> Search keywords Objective-C Generated Interface Header Name, bingo!
  • Johannes
    Johannes over 5 years
    Important note: You can change the module name for each target to make the name of the swift header the same for each target. Details here -> stackoverflow.com/a/27411394/956816
  • SNarula
    SNarula about 5 years
    In my code, after I updated it to Swift 4.2 from swift 3. It's not working
  • Prashant Bhayani
    Prashant Bhayani about 5 years
    what error are you getting? I have used above code in Swift4.2 and its working fine.
  • Chuck Boris
    Chuck Boris about 5 years
    Just want to add that YourProjectName in #import "YourProjectName-Swift.h" will be the name of project from step 8. Useful if your project name contains special characters and you are not sure how exactly you should format it.
  • Mike
    Mike about 4 years
    will this work for structs. I dont believe that they can be derived from NSObject so I am guessing not. I am trying to do this with a constants class
  • Prashant Bhayani
    Prashant Bhayani almost 4 years
    Ok that’s great.
  • user1046037
    user1046037 over 3 years
    The key is using the @objc attribute, wish you could make it in bold, because Apple's documentation doesn't state this properly. Or write it as steps.
  • Iulian  Nikolaiev
    Iulian Nikolaiev almost 3 years
    Thanks a lot! This phrase "Make sure your Swift file is member of the target" saved my day!