267

I try to integrate Swift code in my app.My app is written in Objective-C and I added a Swift class. I've done everything described here. But my problem is that Xcode haven't created the -Swift.h file, only the bridging headers. So I created it, but it's actually empty. I can use all my ObjC classes in Swift, but I can't do it vice versa. I marked my swift class with @objc but it didn't help. What can I do now?

EDIT: Apple says:" When you import Swift code into Objective-C, you rely on an Xcode-generated header file to expose those files to Objective-C. [...] The name of this header is your product module name followed by adding “-Swift.h”. "

Now when I want to import that File, it gives an error:

    //MainMenu.m

    #import "myProjectModule-Swift.h" //Error: 'myProjectModule-Swift.h' file not found

    @implementation MainMenu

Here is my FBManager.swift file:

@objc class FBManager: NSObject {

    var descr = "FBManager class"

    init() {
        super.init()
    }

    func desc(){
        println(descr)
    }

    func getSharedGameState() -> GameState{
        return GameState.sharedGameState() //OK! GameState is written in Objective-C and no error here
    }
}
Ravi Gautam
  • 951
  • 1
  • 9
  • 20
dnnagy
  • 3,460
  • 3
  • 21
  • 31
  • 30
    `YourProjectName-Swift.h` should be a magical header file that Xcode automagically creates for you during compilation (you won't actually see it in the project browser). Try deleting the one you created, and add `#import YourProjectName-Swift.h` to the files in which you want to use the Swift classes. – Greg Jun 13 '14 at 13:44
  • Show the definition of your `Swift` class and how you are accessing it from `Objective-C`. – vacawama Jun 13 '14 at 14:21
  • @vacawama I added some code. I hope it helps. From what I see, I think that the `-Swift.h` file is not created, so I can't include it. – dnnagy Jun 14 '14 at 14:34
  • 3
    Is your app that you are building called `myProjectModule`? The `-Swift.h` file should begin with your app name. Do you have a file ending in `-Bridging-Header.h`? You should. If so, the first part of that file is your project name. Combine the first part of that filename with `-Swift.h` and that is what you should be including. – vacawama Jun 14 '14 at 22:56
  • 4
    I have this successfully working in my project, and yet there is no actual file ending in `-Swift.h` to be found on my Mac, and yet I can include it. So don't get hung up looking for such a file. Just make sure you are naming it correctly. – vacawama Jun 14 '14 at 22:59
  • @PartiallyFinite - Thanks, biggest help to me here was finding out you could not see the Product-Swift.h file in the project browser! Was looking and looking... – Kendall Helmstetter Gelner Jul 15 '14 at 22:05
  • 2
    @vacawama Note that you can see the contents after you add the import statement to an Objective-C file by Command-Clicking on the import as if you were visiting any other header file. – Kendall Helmstetter Gelner Jul 16 '14 at 02:14
  • 7
    I had to use `#import ` – Oliver Pearmain Jul 25 '16 at 11:38
  • Possible duplicate of [How to import Swift code to Objective-C](https://stackoverflow.com/questions/24102104/how-to-import-swift-code-to-objective-c) – ApriOri Jul 30 '17 at 13:45

26 Answers26

529

I spent about 4 hours trying to enable Swift in my Xcode Objective-C based project. My myproject-Swift.h file was created successfully, but my Xcode didn't see my Swift-classes. So, I decided to create a new Xcode Objc-based project and finally, I found the right answer! Hope this post will help someone :-)

Step by step Swift integration for Xcode Objc-based project:

  1. Create new *.swift file (in Xcode) or add it by using Finder.
  2. Create an Objective-C bridging header when Xcode asks you about that.
  3. Implement your Swift class:

    import Foundation
    
    // use @objc or @objcMembers annotation if necessary
    class Foo {
        //..
    }
    
  4. Open Build Settings and check these parameters:

    • Defines Module : YES

      Copy & Paste parameter name in a search bar

    • Product Module Name : myproject

      Make sure that your Product Module Name doesn't contain any special characters

    • Install Objective-C Compatibility Header : YES

      Once you've added *.swift file to the project this property will appear in Build Settings

    • Objective-C Generated Interface Header : myproject-Swift.h

      This header is auto-generated by Xcode

    • Objective-C Bridging Header : $(SRCROOT)/myproject-Bridging-Header.h
  5. Import Swift interface header in your *.m file.

    #import "myproject-Swift.h"
    

    Don't pay attention to errors and warnings.

  6. Clean and rebuild your Xcode project.
  7. Profit!
sig
  • 5,896
  • 2
  • 24
  • 31
  • 2
    Has anyone seen mention of the configuration required (at least for me) in the documentation at: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_77 in step 4 above? If it is I missed it. Thanks @sig. – Morkrom Dec 15 '14 at 21:55
  • In my case the _swift.h file is not even created in my DerivedSources folder. Of course I cannot compile regularly as the fact the swift class is not found produces errors. Should I remove the swift classes and the calls to them, rebuild and then readd the file and calls again? – Fabrizio Bartolomucci Jan 14 '15 at 10:27
  • Ok, I did remove the references to the swift files but not the files and I think came closer to the problem. Now the compiler complaints that: the SDK 'iPhoneOS7.1.sdk' does not support Swift, whatever that may mean. I searched on the net for the full sentence but strangely found nothing. Any hint? – Fabrizio Bartolomucci Jan 14 '15 at 18:39
  • 2
    My problem was much simpler - I couldn't find the file `"myproject-Swift.h"` so it seems to me like it's not working. Apparently, this file is not visible in the project navigator. – Asaf May 22 '15 at 00:10
  • 7
    @Asaf Actually, yes, this file is auto-genereting by Xcode and locating in your project build-path. So, you can find this file manually in Finder/Console or open it directly in Xcode by using Cmd+LeftClick on `#import "myproject-Swift.h"`. – sig May 22 '15 at 12:08
  • 2
    As for me #5 was enough to fix problem!! – skywinder May 29 '15 at 11:31
  • Install Objective-C Compatibility Header : YES. I don't have this in my Build Settings. And I don't even have any swift compiler available in my Build Settings. You said you created the Obj-c based project but this solutions does not work for me. – SnowWolf Jun 07 '15 at 16:27
  • @SnowWolf You sure that you chose right target? Try to use search in Build Settings and paste those sentences. – sig Jun 07 '15 at 17:58
  • I have two targets in my project. So product names are different. #import "myproject-Swift.h" needs to be edited when I build target. Like #import "myproject1-Swift.h" and #import "myproject2-Swift.h". Can I avoid this edit work with some generic tag. – Durgaprasad Oct 27 '15 at 05:22
  • Embedded content contains swift code can be NO. Defines Modules can be NO. If your class subclasses an Objective-C class, you definitely do NOT need the @objc tag. – Dan Rosenstark Feb 03 '16 at 17:31
  • 14
    With your those 4 hours, you saved hundred of our hours, Thanks a lot :) Saved in my Favorite ;) – Abo3atef Mar 13 '16 at 15:26
  • 1
    If nothing helps - check `@import swiftClassName;` (swiftClassName.swift) – Nik Kov Jun 15 '16 at 10:48
  • Refer this article.It expains nicely:http://pinkstone.co.uk/how-to-use-swift-classes-in-objective-c/ – NSS Aug 05 '16 at 13:44
  • After 2 hours of struggle, I found my mistake: once I created my .swift file, xcode didn't generate a -Swift.h file for me (it did, but the file is not visible in the project anyhow), so I created it by myself x_x. Guys, it's a trap! Never create -Swift.h file by hand! Xcode will include this file from only-god-knows-where by itself. – Alexey Kureev Nov 03 '16 at 21:39
  • I got my project running and everything is working fine. Only thing is without adding prefix "@objc" the app is running properly. So is it really required to add this prefix to classes? – Dharmesh Siddhpura Nov 13 '16 at 22:25
  • Argh, forgetting to clean the project (6) was my bane. – qix Dec 23 '16 at 08:45
  • Please I can't find Install Objective-C Compatibility Header. I use Xcode 8 – Ne AS Feb 06 '17 at 14:57
  • @Llg In Xcode 8.2.1 open Build Settings tab and paste "Install Objective-C Compatibility Header" in the Search field. – sig Feb 07 '17 at 10:44
  • Re. special characters in the module/project name, my problem was a hyphen in the project name (beyond my control). The Swift interface header replaced the hyphen with an underscore, which I hadn't realised. – Echelon Jun 23 '17 at 12:05
  • I only did #5 #import "myproject-Swift.h" and it solved the problem. I didn't do anything else. – coolcool1994 Sep 20 '17 at 03:34
  • 1
    Just didn't work for me. All I did was adding one .swift file to a project via Finder d'n'd to Xode, accepted the Bridging Header creation, followed steps, and I still get the error that '-Swift.h' import cannot be found. – mixtly87 Sep 20 '17 at 18:16
  • Did everything as outlined. Still not working. Trying to add Charts for iOS Swift project to my Objective-C project and getting error module-Swift.h not found. – Dalmazio Oct 01 '17 at 21:23
  • @mixtly87 Build your project and error will disappear – sig Oct 02 '17 at 09:31
  • @Dalmazio Use Cocoapods. Otherwise check the Usage section in Readme file inside repository and use `@import Charts`. – sig Oct 02 '17 at 09:35
  • So something strange. It seems that Xcode was indexing, and while indexing, compiling gave the error that it can't find the Swift framework headers for #import'ing into Objective-C source. Maybe I was too impatient. After starting over, cleaned all changes and letting it finish index, it worked. Anyway, thanks @sig for the heads up. – Dalmazio Oct 03 '17 at 03:00
  • Didn't work for me until I changed the import directive from ```#import "YourProjectName-Swift.h"``` to ```#import ```. – chmaynard Nov 28 '17 at 13:25
  • Changing Product Name in Build Setting to My project name with Defines Module set to YES worked for me !!!! – Vinod Supnekar Dec 13 '17 at 09:42
  • Point 5 saved my day :-) – Karsten Jan 23 '18 at 07:20
  • xcode doesn't ask me about `Create an Objective-C bridging header when Xcode ask you about that` when I create swift class! – user924 Apr 02 '18 at 11:48
  • @user924 I checked that this message is displayed on `Xcode 9.3`. I can only suggest you to add file manually: `project/project-Bridging-Header.h`. And carefully follow the instructions in paragraph 4. – sig Apr 03 '18 at 14:44
69

Don't create the header file yourself. Delete the one you created.

Make sure your Swift classes are tagged with @objc or inherit from a class that derives (directly or indirectly) from NSObject.

Xcode won't generate the file if you have any compiler errors in your project - make sure your project builds cleanly.

Bill
  • 38,492
  • 24
  • 114
  • 205
  • 8
    being build-able was the key for me. Couldn't build because it couldn't find my -swift.h file, but it couldn't find my -swift.h file because it couldn't build :/ – anders Dec 03 '15 at 22:39
  • 13
    @anders while trapped in that cycle, you can use `find ~/library/Developer/Xcode/DerivedData/ -name "*-Swift.h"|xargs basename|sort -u` to see if the file was created with an unexpected name like it was for me. :) – CodeReaper Jan 13 '16 at 12:28
  • Make sure, that ```*-Bridging-Header.h``` file is also created, not only ```*-Swift.h``` file. It is critical to have it, even if it is empty. If it is not created, create it yourself and add it to the project build settings for ```Objective-C Bridging Header``` value. – Denis Kutlubaev Jun 29 '20 at 10:07
39

Allow Xcode to do its work, do not add/create Swift header manually. Just add @objc before your Swift class ex.

@objc class YourSwiftClassName: UIViewController

In your project setting search for below flags and change it to YES (Both Project and Target)

Defines Module : YES
Always Embed Swift Standard Libraries : YES
Install Objective-C Compatibility Header : YES

Then clean the project and build once, after build succeed (it should probably) import below header file in your objective-c class .m file

#import "YourProjectName-Swift.h" 

Boooom!

Bharat Modi
  • 3,998
  • 2
  • 13
  • 26
29

Also probably helpful for those of you with a Framework target:

The import statement of the auto-generated header file looks a bit different from app targets. In addition to the other things mentioned in other answers use

#import <ProductName/ProductModuleName-Swift.h>

instead of

#import "ProductModuleName-Swift.h"

as per Apples documentation on Mix & Match for framework targets.

Jeehut
  • 15,556
  • 7
  • 54
  • 70
14

Make sure your project defines a module and you have given a name to the module. Then rebuild, and Xcode will create the -Swift.h header file and you will be able to import.

You can set module definition and module name in your project settings.

Leo Natan
  • 55,734
  • 8
  • 140
  • 186
14

Details: Objective-C project with Swift 3 code in Xcode 8.1

Tasks:

  1. Use swift enum in objective-c class
  2. Use objective-c enum in swift class

FULL SAMPLE

1. Objective-C class which use Swift enum

ObjcClass.h

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, ObjcEnum) {
    ObjcEnumValue1,
    ObjcEnumValue2,
    ObjcEnumValue3
};

@interface ObjcClass : NSObject

+ (void) PrintEnumValues;

@end

ObjcClass.m

#import "ObjcClass.h"
#import "SwiftCode.h"

@implementation ObjcClass

+ (void) PrintEnumValues {
    [self PrintEnumValue:SwiftEnumValue1];
    [self PrintEnumValue:SwiftEnumValue2];
    [self PrintEnumValue:SwiftEnumValue3];
}

+ (void) PrintEnumValue:(SwiftEnum) value {
    switch (value) {
        case SwiftEnumValue1:
            NSLog(@"-- SwiftEnum: SwiftEnumValue1");
            break;
            
        case SwiftEnumValue2:
        case SwiftEnumValue3:
            NSLog(@"-- SwiftEnum: long value = %ld", (long)value);
            break;
    }
}

@end

Detect Swift code in Objective-C code

In my sample I use SwiftCode.h to detect Swift code in Objective-C. This file generate automatically (I did not create a physical copy of this header file in a project), and you can only set name of this file:

enter image description here

enter image description here

If the compiler can not find your header file Swift code, try to compile the project.

2. Swift class which use Objective-C enum

import Foundation

@objc
enum SwiftEnum: Int {
    case Value1, Value2, Value3
}

@objc
class SwiftClass: NSObject {
    
    class func PrintEnumValues() {
        PrintEnumValue(.Value1)
        PrintEnumValue(.Value2)
        PrintEnumValue(.Value3)
    }
    
    class func PrintEnumValue(value: ObjcEnum) {
        switch value {
        case .Value1, .Value2:
            NSLog("-- ObjcEnum: int value = \(value.rawValue)")
            
        case .Value3:
            NSLog("-- ObjcEnum: Value3")
            break
        }
        
    }
}

Detect Objective-C code in Swift code

You need to create bridging header file. When you add Swift file in Objective-C project, or Objective-C file in swift project Xcode will suggest you to create bridging header.

enter image description here

You can change bridging header file name here:

enter image description here

Bridging-Header.h

#import "ObjcClass.h"

Usage

#import "SwiftCode.h"
...
[ObjcClass PrintEnumValues];
[SwiftClass PrintEnumValues];
[SwiftClass PrintEnumValue:ObjcEnumValue3];

Result

enter image description here


MORE SAMPLES

Full integration steps Objective-c and Swift described above. Now I will write some other code examples.

3. Call Swift class from Objective-c code

Swift class

import Foundation

@objc
class SwiftClass:NSObject {
    
    private var _stringValue: String
    var stringValue: String {
        get {
            print("SwiftClass get stringValue")
            return _stringValue
        }
        set {
            print("SwiftClass set stringValue = \(newValue)")
            _stringValue = newValue
        }
    }
    
    init (stringValue: String) {
        print("SwiftClass init(String)")
        _stringValue = stringValue
    }
    
    func printValue() {
        print("SwiftClass printValue()")
        print("stringValue = \(_stringValue)")
    }
    
}

Objective-C code (calling code)

SwiftClass *obj = [[SwiftClass alloc] initWithStringValue: @"Hello World!"];
[obj printValue];
NSString * str = obj.stringValue;
obj.stringValue = @"HeLLo wOrLd!!!";

Result

enter image description here

4. Call Objective-c class from Swift code

Objective-C class (ObjcClass.h)

#import <Foundation/Foundation.h>

@interface ObjcClass : NSObject
@property NSString* stringValue;
- (instancetype) initWithStringValue:(NSString*)stringValue;
- (void) printValue;
@end

ObjcClass.m

#import "ObjcClass.h"

@interface ObjcClass()

@property NSString* strValue;

@end

@implementation ObjcClass

- (instancetype) initWithStringValue:(NSString*)stringValue {
    NSLog(@"ObjcClass initWithStringValue");
    _strValue = stringValue;
    return self;
}

- (void) printValue {
    NSLog(@"ObjcClass printValue");
    NSLog(@"stringValue = %@", _strValue);
}

- (NSString*) stringValue {
    NSLog(@"ObjcClass get stringValue");
    return _strValue;
}

- (void) setStringValue:(NSString*)newValue {
    NSLog(@"ObjcClass set stringValue = %@", newValue);
    _strValue = newValue;
}

@end

Swift code (calling code)

if let obj = ObjcClass(stringValue:  "Hello World!") {
    obj.printValue()
    let str = obj.stringValue;
    obj.stringValue = "HeLLo wOrLd!!!";
}

Result

enter image description here

5. Use Swift extension in Objective-c code

Swift extension

extension UIView {
    static func swiftExtensionFunc() {
        NSLog("UIView swiftExtensionFunc")
    }
}

Objective-C code (calling code)

[UIView swiftExtensionFunc];

6. Use Objective-c extension in swift code

Objective-C extension (UIViewExtension.h)

#import <UIKit/UIKit.h>

@interface UIView (ObjcAdditions)
+ (void)objcExtensionFunc;
@end

UIViewExtension.m

@implementation UIView (ObjcAdditions)
+ (void)objcExtensionFunc {
    NSLog(@"UIView objcExtensionFunc");
}
@end

Swift code (calling code)

UIView.objcExtensionFunc()
Community
  • 1
  • 1
Vasily Bodnarchuk
  • 19,860
  • 8
  • 111
  • 113
  • These samples are really helpful, thank you! And as for Swift 4+, we need to add `@objcMembers` in front of the class. Because `@objc` inference have been reduced in Swift 4 for optimization purpose. For instance, a property within an NSObject-derived class, will no longer infer @objc by default (as it did in Swift 3). I got this intel from [this answer](https://stackoverflow.com/a/45656756/4394850). – Hustlion Apr 12 '19 at 10:52
11

I had the same issue and it turned out special symbols in the module name are replaced by xcode (in my case dashes ended up being underscores). In project settings check "module name" to find the module name for your project. After that either use ModuleName-Swift.h or rename the module in settings.

Max Mikheyenko
  • 235
  • 1
  • 3
  • 17
9

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

brainray
  • 11,429
  • 10
  • 60
  • 109
8

Just include #import "myProject-Swift.h" in .m or .h file

P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.

Svitlana
  • 2,670
  • 1
  • 26
  • 34
  • Thanks for the heads up, mate. – Felipe Apr 12 '16 at 16:02
  • This answer helped me and saved my day. The important thing is than Xcode is generating it automatically and it's HIDDEN file. I was creating "myProject-Swift.h" myself and it was not working. – C0mrade Oct 10 '16 at 10:38
7

For Swift 5:

  1. Add the @objc keyword to your class and methods
  2. Add public keyword to your class and methods
  3. Let your class inherit from NSObject
  4. Build Project
  5. Put #import "MyProject-Swift.h" in your Objective-C file

    @objc
    public class MyClass: NSObject {
    
        @objc
        public func myMethod() {
    
        }
    }
    
Nico S.
  • 2,023
  • 1
  • 22
  • 49
6

@sig answer is one of the best, however, it did not work for me with the old project (not new!), I needed some modifications. After a lot of variations I found the recipe for me (using XCode 7.2):

  1. Product Module Name : $(PRODUCT_NAME:c99extidentifier)
  2. Defines Module : NO
  3. Embedded Content Contains Swift : NO
  4. Install Objective-C Compatibility Header : YES
  5. Objective-C Bridging Header : ProjectName-Bridging-Header.h

The last point (5) was crucial. I put it only on the second section (Targets field), the Project field should be left empty: enter image description here Otherwise, it did not generate the right "Project-Swift.h" file for me (it did not include swift methods).

Darius Miliauskas
  • 3,039
  • 4
  • 29
  • 48
5

There is two condition,

  • Use your swift file in objective c file.
  • Use your objective c file in swift file.

So, For that purpose, you have to follow this steps:

  • Add your swift file in an objective-c project or vice-versa.
  • Create header(.h) file.
  • Go to Build Settings and perform below steps with search,

    1. search for this text "brid" and set a path of your header file.
    2. "Defines Module": YES.
    3. "Always Embed Swift Standard Libraries" : YES.
    4. "Install Objective-C Compatibility Header" : YES.

After that, clean and rebuild your project.

Use your swift file in objective c file.

In that case,First write "@objc" before your class in swift file.

After that ,In your objective c file, write this,

  #import "YourProjectName-Swift.h"

Use your objective c file in swift file.

In that case, In your header file, write this,

  #import "YourObjective-c_FileName.h"

I hope this will help you.

vikas prajapati
  • 1,674
  • 14
  • 23
3

In my case, apart from these steps:

  1. Product Module Name : myproject
  2. Defines Module : YES
  3. Embedded Content Contains Swift : YES
  4. Install Objective-C Compatibility Header : YES
  5. Objective-C Bridging Header : $(SRCROOT)/Sources/SwiftBridging.h

I have needed to put the class as public in order to create productName-Swift.h file:

import UIKit

   @objc public class TestSwift: NSObject {
       func sayHello() {
          print("Hi there!")
       }
   }
93sauu
  • 2,762
  • 3
  • 19
  • 39
2

I just discovered that adding a directory of swift files to a project won't work. You need to create a group first for the directory, then add the swift files...

Darren Ehlers
  • 634
  • 6
  • 16
2

I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.

Hope this helps someone.

Dani.Rangelov
  • 366
  • 2
  • 5
1

my problem was I got stuck after xcode created the bridge file but still I got error in header file name MYPROJECTNAME-swift.h

1.I check in terminal and search for all auto created swift bridge files:

find ~/library/Developer/Xcode/DerivedData/ -name "*-Swift.h"|xargs basename|sort -

you see what xcode created.

  1. in my case, I had space in my project name and xcode replace this is '_'
qix
  • 6,008
  • 1
  • 44
  • 58
user1105951
  • 2,117
  • 2
  • 28
  • 53
1

When you add new Swift files to the project, please, make sure that you add them to correct targets. Please, make sure that every swift file you're going to use inherits NSObject class and annotated with @ObjCMembers Change to YES inside the build settings under the option ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES. Change to YES inside the build settings under the option DEFINES_MODULE.

Boris
  • 314
  • 5
  • 20
0

I have the same error: myProjectModule-Swift.h file not found", but, in my case, real reason was in wrong deployment target: "Swift is unavailable on OS X earlier than 10.9; please set MACOSX_DEPLOYMENT_TARGET to 10.9 or later (currently it is '10.7')" so, when I've changed deployment target to 10.9 - project had been compiled successfully.

Ravi Gautam
  • 951
  • 1
  • 9
  • 20
slavik
  • 1,328
  • 2
  • 11
  • 13
0

My issue was that the auto-generation of the -swift.h file was not able to understand a subclass of CustomDebugStringConvertible. I changed class to be a subclass of NSObject instead. After that, the -swift.h file now included the class properly.

Justin Domnitz
  • 2,994
  • 24
  • 30
0

I had issues in that I would add classes to my objective-c bridging header, and in those objective-c headers that were imported, they were trying to import the swift header. It didn't like that.

So in all my objective-c classes that use swift, but are also bridged, the key was to make sure that you use forward class declarations in the headers, then import the "*-Swift.h" file in the .m file.

horseshoe7
  • 2,629
  • 2
  • 29
  • 43
0

I didnt have to change any settings in the build or add @obj to the class.

All I had to do was to create bridge-header which was automatically created when I created Swift classes into Objective-c project. And then I just had to do

import "Bedtime-Swift.h" <- inside objective-c file that needed to use that swift file.

Community
  • 1
  • 1
coolcool1994
  • 3,085
  • 3
  • 32
  • 38
0

well, after reading all the comments and trying and reading and trying again, I managed to include swift classes into my Big obj-c project. So, thanks for all the help. I wanted to share one tip that helped me understand the process better. In the .m class, went to the import line of the swift target name #import "myTargetName-Swift.h" and clicked the key:

command + mouse click -> Jump to definition enter image description here

There you can see all the translation from swift to obj-c and ther you will find the various functions re-declared in obj-c. Hope this tip will help you as much as it helped me.

Techno Mag
  • 21
  • 4
0

Using Swift Classes in Objective-C

If you are going to import code within an App Target (Mixing Objective-C and Swift in one project) you should use the next import line #import "<#YourProjectName#>-Swift.h" to expose Swift code to Objective-C code [Mixing Swift and Objective-C code in a project]

In this post I will describe how to import Swift static library to Objective-C code

Objective-C consumer -> Swift static library

Xcode version 10.2.1

Create Swift static library

Follow Create Swift static library with next additions:

Expose Swift API. To use Swift's functions from Objective-C[About]

After building you should find a <product_name>-Swift.h file that should be located into DerivedSources [File not found]

Objective-C consumer with Swift static library

Drag and drop the binary into the Xcode project[About]

Link Library[Undefined symbols] [Link vs Embed]

Project editor -> select a target -> General -> Linked Frameworks and Libraries -> add -> Add Others... -> point to `lib<product_name>.a` file
//or
Project editor -> select a target -> Build Phases -> Link Binary With Libraries -> add -> Add Others... -> point to `lib<product_name>.a` file

Add Library Search paths[Library not found for] [Recursive path]

Project editor -> select a target -> Build Settings -> Search Paths -> Library Search paths -> add path to the parent of `lib<product_name>.a` file

Add Header Search Paths[Module not found] [Recursive path]

Project editor -> select a target -> Build Settings -> Search Paths -> Header Search Paths -> add path to generated `<product_name>-Swift.h` file 

Add empty .swift file to the Objective-C project.[Undefined symbols] When Xcode ask press Create Bridging Header(it will create module_name-Bridging-Header.h) and setup a path to this file in

Project editor -> select a target -> Build Settings -> Swift Compiler - General -> Objective-C Bridging Header

Import module to the Objective-C client code[File not found] [module_name]

#import "module_name-Swift.h"

More examples here

yoAlex5
  • 13,571
  • 5
  • 105
  • 98
0

XCode 11.3.1:

When I want to use an Swift inner class in a objc code, it does not compile for ther error "undefined symbol"(for bother inner class and outer class), I checked the generated "-swift.h" header and both classes are there.

After trying for hours I convert the inner class to a normal class and it compiles.

I clean the project, delete the DerivedData folder and it compiles.

Bill Chan
  • 2,416
  • 27
  • 26
0

I use CocoaPods and the Swift class from my library couldn't be located from the Objective-C code in the example app because it's project and target were named the same as the library, so I had to remove the Objective-C Generated Interface Name values so they didn't conflict with the ones from the library.

-1

After doing everything above, I still got errors. My problem ended up being that the Swift files I needed weren't added to the bundle resources for some reason.

I fixed this by going to [MyTarget] > Build Phases > Copy Bundle Resources, then clicked the plus button and added the Swift files.

onemoreanimal
  • 97
  • 1
  • 4