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?
#i
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.
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"
.
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.
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/
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.
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"
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.