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) :
I have set Defines Module to Yes
The syntax for importing Swift code within a framework target is
which in your case would probably be
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
oropen
access modifier in order to be visible via the-Swift.h
interface header. You also need to make theaddTest()
function callable from Objective-C, hence the need for@objc
in front of it. So, your Swift code should be changed like this: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 droppingpublic
:(you still need
@objc
, though).Then in your Objective-C class you could do:
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.