Jhonsore
Jhonsore

Reputation: 1857

Objc class doesn't recognize Swift class

I could not import swift class inside my objective c project following these steps:

Enviroment:

Xcode: 10.0

Swift: 4.2

1 - Ctrl+N to generate a new swift file

2 - Selected “Create Bridging Header” from xcode question

3 - On Target -> build settings, search for "Packaging" and turn on "Defines Module"

4 - Imported #import "MyProjectModuleName-Swift.h" in my objc .m file

5 - Trying to call my swift method and nothing seems to work, i'm not capable to call it because my .m class doesn't recognize my .swift file.

Whats wrong?

Upvotes: 0

Views: 1050

Answers (1)

Jhonsore
Jhonsore

Reputation: 1857

I was trying to use an swift class inside an objective c project and spent a lot of time trying to make it works with no success.

All answer didn't work for me until i got the right path for my Project-Swift.h.

That was the trick that saved my life.


Follow this steps and you will success!

1 - Create your xcode project

2 - Create a new .swift file

3 - A dialogue box will appear, make sure to select “Create Bridging Header” when prompted.

4 - On Target -> build settings, search for "Packaging" and turn on "Defines Module"

5 - On your swift file (sample)

import Foundation

@objcMembers

class MyClass: NSObject {
    public func test () -> String {
        return "Swift says hi to objc class!"
    }
}

Here pay attention to @objcMembers that will let objc class recognize swift class!

Find it here

6 - On your objc class .m or .h file import your auto generated Project-Swift.h file on step 3

My goal was to import it:

#import <Teste-Swift.h>

And not:

#import "Teste-Swift.h"

Thats it, after a headache i got tha answer

So at the end, my .m file was like this:

#import "ViewController.h"
#import <Teste-Swift.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //-------------        
    MySwiftClass *myswiftclass = [[MySwiftClass alloc] init];
    NSString *string = [myswiftclass test];
    NSLog(@"%@",string);
}


@end

An my .swift file:

import Foundation

@objcMembers

class MySwiftClass: NSObject {
    public func test () -> String {
        return "Swift says hi second swift class!"
    }
}

I hope this can help you folks.

Upvotes: 1

Related Questions