Swift framework - Objective-C header not found

1.6k views Asked by At

I created a small test framework in Swift. My purpose is to use Swift class in Objective-C class. I created a Swift file. And then an Objective-C file. I made sure that the Objective-C header in Build Settings is Test-Swift.h
When I try to import Test-Swift.h in objective-C file, I get an error -

'Test-Swift.h' file not found.

Swift class :

import Foundation

@objc class MyTest: NSObject {
    func addTest()  {
        print("test")
    }
}  

Objective-C class :

#import "YourTest.h"
#import <Test/Test-Swift.h>
#import "Test-Swift.h"       // Error in this line

@implementation YourTest

-(void)testTest {
    // This is how I want to use the swift class
    MyTest *test = [MyTest new];
    [test addTest];

}

@end  

Framework header :

#import <UIKit/UIKit.h>

//! Project version number for Test.
FOUNDATION_EXPORT double TestVersionNumber;

//! Project version string for Test.
FOUNDATION_EXPORT const unsigned char TestVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Test/PublicHeader.h>  

Build setting (objective-C header) :

enter image description here

I have set Defines Module to Yes

1

There are 1 answers

0
Anatoli P On

The syntax for importing Swift code within a framework target is

#import <ProductName/ProductModuleName-Swift.h>

which in your case would probably be

#import <Test/Test-Swift.h>

This line is, actually, present in your example and the compiler evidently doesn't complain about it. See https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_swift_into_objective-c.

Another problem is that you won't be able to use your Swift class the way you are trying to, given the Swift declaration. According to the above reference, the Swift declarations would need to have public or open access modifier in order to be visible via the -Swift.h interface header. You also need to make the addTest() function callable from Objective-C, hence the need for @objc in front of it. So, your Swift code should be changed like this:

@objc public class MyTest: NSObject {
    @objc public func addTest()  {
        print("test")
    }
}  

Based on the same documentation referenced above, you could make it more difficult for Objective-C code outside of the framework to access addTest() by dropping public:

@objc func addTest()...

(you still need @objc, though).

Then in your Objective-C class you could do:

[test performSelector:@selector(addTest)];

However, any code outside of the framework can do the same thing.

Another observation is that the line of code that caused the error in your example, i.e. #import "Test-Swift.h", is a way to include the interface header in an application target as opposed to a framework.