328

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
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Dark Matter
  • 3,638
  • 3
  • 14
  • 14
  • 10
    love this project! – SleepsOnNewspapers Apr 25 '15 at 03:19
  • 1
    Answer to this question can be found in the Apple documentation itself: https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_swift_into_objective-c I recommend to read the documentation first before reading all the answers. – Vin Feb 12 '21 at 13:55

16 Answers16

517

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

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Bill
  • 44,502
  • 24
  • 122
  • 213
  • 5
    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". – louielouie Jun 09 '14 at 22:10
  • 1
    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. Jul 17 '14 at 15:22
  • 8
    EDIT: **Note:** for this to work, a project module name MUST be defined. See: http://stackoverflow.com/a/24064015/2085743 – Ruben Martinez Jr. Jul 17 '14 at 15:34
  • 7
    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" – Hola Soy Edu Feliz Navidad Dec 04 '14 at 04:27
  • Hi @Bill how do i use swift library through cocoapod in my objective c project...? – Hardik Amal Sep 07 '15 at 14:50
  • 1
    How does this work in a Framework target, can you just add #import to the umbrella header? – marchinram Sep 14 '15 at 22:42
  • 121
    Why is this so hard and poorly documented? – uchuugaka Nov 01 '15 at 06:43
  • @HardikAmal you can still use, for example, `#import "SCLAlertView-Swift.h"` in Objective-C class, or `@import ;` – Raptor Dec 21 '15 at 09:53
  • @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. – Amit Saxena Jun 29 '16 at 07:49
  • I have used `#import "SCLAlertView-Swift.h"` in `.m` and I getting error: `SCLAlertView-Swift.h not found`, I did something wrong? – Aamir Apr 22 '17 at 06:41
  • @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? – Aamir Apr 22 '17 at 13:33
  • @Aamir Actually, it's the target name, not the project name. Let me update my answer. – Bill Apr 22 '17 at 13:36
  • @Bill my project name is same as target name. – Aamir Apr 22 '17 at 13:37
  • I did this but I get 10 compile errors saying that `No type or protocol UIApplicationDelegate` and similar – fnc12 Aug 01 '17 at 05:26
  • Do you have to import it in your .m file? – John Franke Jan 03 '18 at 20:55
  • @JohnOttenlips yes – Bill Jan 03 '18 at 21:27
  • This auto-generated file is now called `TargetName-Bridging-Header.h` though? – lelelo Jan 29 '18 at 19:31
  • 3
    @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. – Bill Jan 30 '18 at 00:36
  • 2
    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 – atulkhatri Mar 19 '18 at 05:59
  • @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? – Adeel Miraj Sep 04 '18 at 11:03
  • 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. – Bill Sep 04 '18 at 11:05
  • 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. – Adeel Miraj Sep 04 '18 at 11:21
  • 8
    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! – Itachi Dec 21 '18 at 03:36
  • **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 -> https://stackoverflow.com/a/27411394/956816 – Johannes Feb 11 '19 at 16:02
  • 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. – user1046037 Jan 30 '21 at 04:35
  • Thanks a lot! This phrase "Make sure your Swift file is member of the target" saved my day! – Iulian Nikolaiev Aug 11 '21 at 14:15
177

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"

Papershine
  • 4,995
  • 2
  • 24
  • 48
Sumit singh
  • 2,398
  • 1
  • 15
  • 30
170

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

Andrei Papancea
  • 2,214
  • 1
  • 15
  • 12
  • 2
    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'?" – Alphonse R. Dsouza Aug 13 '15 at 12:17
  • 1
    @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. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0 – Alejandro Iván Jan 14 '16 at 17:05
  • 1
    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` – David T. Dec 08 '16 at 01:50
  • Worth reading this answer for some cases: http://stackoverflow.com/questions/26328034/importing-project-swift-h-into-a-objective-c-class-file-not-found Depending on what you are doing: #import #import #import – inigo333 Apr 03 '17 at 10:19
  • What if you want import a Swift extension? – Ricardo Aug 30 '17 at 23:00
  • In my case `"ProductName-Swift.h"` works perfect in `xcode 7.3` but now works in `xcode 8.3.2` – jose920405 Sep 05 '17 at 18:25
  • @AlejandroIván I have UIView swift class will it work ? I am not able to import swift into objective c – Darshan Mothreja Jan 05 '18 at 22:47
  • 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". – Martin-Gilles Lavoie Mar 13 '18 at 20:40
  • "Note that you cannot subclass a Swift class in Objective-C." Thank you for including this, it saved me from going crazy. – Tamás Sengel Nov 08 '18 at 14:39
  • 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 – Mike May 16 '20 at 00:35
47

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

KingPolygon
  • 4,753
  • 7
  • 43
  • 72
25

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.

Lukas Kalinski
  • 2,213
  • 24
  • 26
17

Importing Swift file inside Objective-c can cause this error, if it doesn't import properly.

NOTE: You don't have to import Swift files externally, you just have to import one file which takes care of swift files.

When you Created/Copied Swift file inside Objective-C project. It would've created a bridging header automatically.

Check Objective-C Generated Interface Header Name at Targets -> Build Settings.

enter image description here

Based on above, I will import KJExpandable-Swift.h as it is.

Your's will be TargetName-Swift.h, Where TargetName differs based on your project name or another target your might have added and running on it.

As below my target is KJExpandable, so it's KJExpandable-Swift.h
enter image description here

Kiran Jasvanee
  • 6,362
  • 1
  • 36
  • 52
15

First Step:-

Select Project Target -> Build Setting -> Search('Define') -> Define Module update value No to Yes

"Defines Module": YES.

"Always Embed Swift Standard Libraries" : YES.

"Install Objective-C Compatibility Header" : YES.

enter image description here

Second Step:-

Add Swift file Class in Objective C ".h" File as below

#import <UIKit/UIKit.h>

@class TestViewController(Swift File);

@interface TestViewController(Objective C File) : UIViewController

@end

Import 'ProjectName(Your Project Name)-Swift.h' in Objective C ".m" file

//TestViewController.m 
#import "TestViewController.h"

/*import ProjectName-Swift.h file to access Swift file here*/

#import "ProjectName-Swift.h"
Darshan Panchal
  • 277
  • 3
  • 5
14

If you have a project created in Swift 4 and then added Objective-C files, do it like this:

@objcMembers
public class MyModel: NSObject {
    var someFlag = false         
    func doSomething() {         
        print("doing something")
    }
}

Reference: https://useyourloaf.com/blog/objc-warnings-upgrading-to-swift-4/

Prashant Bhayani
  • 692
  • 5
  • 18
11

There's one caveat if you're importing Swift code into your Objective-C files within the same framework. You have to do it with specifying the framework name and angle brackets:

#import <MyFramework/MyFramework-Swift.h>

MyFramework here is the "Product Module Name" build setting (PRODUCT_NAME = MyFramework).

Simply adding #import "MyFramework-Swift.h" won't work. If you check the built products directory (before such an #import is added, so you've had at least one successful build with some Swift code in the target), then you should still see the file MyFramework-Swift.h in the Headers directory.

Misha Karpenko
  • 2,168
  • 17
  • 18
7

Be careful with dashes and underscores, they can be mixed up and your Project Name and Target name won't be the same as SWIFT_MODULE_NAME.

Dashes and underscores

Naloiko Eugene
  • 2,453
  • 1
  • 28
  • 18
5

Checkout the pre-release notes about Swift and Objective C in the same project

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75

You should be importing

#import "SCLAlertView-Swift.h"
Nitin Alabur
  • 5,812
  • 1
  • 34
  • 52
  • 3
    Showed me this error: 'SCLAlertView-Swift.h' file not found. – Dark Matter Jun 08 '14 at 01:32
  • 2
    Needs to be the project name, not the filename - see my answer. – Bill Jun 08 '14 at 04:02
  • 1
    Thanks for the documentation link. That was useful for reference. – louielouie Jun 09 '14 at 22:09
  • 2
    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 – Chris May 24 '15 at 13:41
4

Search for "Objective-C Generated Interface Header Name" in the Build Settings of the target you're trying to build (let's say it's MyApp-Swift.h), and import the value of this setting (#import "MyApp-Swift.h") in the source file where you're trying to access your Swift APIs.

The default value for this field is $(SWIFT_MODULE_NAME)-Swift.h. You can see it if you double-click in the value field of the "Objective-C Generated Interface Header Name" setting.

Also, if you have dashes in your module name (let's say it's My-App), then in the $(SWIFT_MODULE_NAME) all dashes will be replaced with underscores. So then you'll have to add #import "My_App-Swift.h".

Misha Karpenko
  • 2,168
  • 17
  • 18
3

If you want to use Swift file into Objective-C class, so from Xcode 8 onwards you can follow below steps:

If you have created the project in Objective-C:

  1. Create new Swift file
  2. Xcode will automatically prompt for Bridge-Header file
  3. Generate it
  4. Import "ProjectName-Swift.h" in your Objective-C controller (import in implementation not in interface) (if your project has space in between name so use underscore "Project_Name-Swift.h")
  5. You will be able to access your Objective-C class in Swift.

Compile it and if it will generate linker error like: compiled with newer version of Swift language (3.0) than previous files (2.0) for architecture x86_64 or armv 7

Make one more change in your

  1. Xcode -> Project -> Target -> Build Settings -> Use Legacy Swift Language Version -> Yes

Build and Run.

Dheeraj D
  • 4,386
  • 4
  • 20
  • 34
1
#import <TargetName-Swift.h>

you will see when you enter from keyboard #import < and after automaticly Xcode will advice to you.

Erhan Demirci
  • 4,173
  • 4
  • 36
  • 44
0

only some tips about syntax, about Xcode everything has been said

  1. you cannot import 'pure" functions, only classes, even if marked "public", so:

    public func f1(){ print("f1"); }

will NOT be called in ANY way.

  1. If You write classes., add inheritance from NSObject, other will NOT be usable.

  2. if it inherits from NSObject, as below:

    class Utils : NSObject{

    static func aaa()->String{ return "AAA" }

    @objc static func bbb()->String{ return "BBB" }

    @objc private static func ccc()->String{ return "CCC" }

    }

in OBJC:

aaa() NOT called: "No known class method for selector 'aaa'"

bbb() ok

ccc() NOT called: "No known class method for selector 'aaa'"

ingconti
  • 10,876
  • 3
  • 61
  • 48
-2

Find the .PCH file inside the project. and then add #import "YourProjectName-Swift.h" This will import the class headers. So that you don't have to import into specific file.

#ifndef __IPHONE_3_0
#warning "This project uses features only available in iPhone SDK 3.0 and later."
#endif


#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "YourProjectName-Swift.h"
#endif
Ram G.
  • 3,045
  • 2
  • 25
  • 31