Error After Importing Swift into Objective-C

How can I import Swift code to Objective-C?

You need to import ProductName-Swift.h. Note that it's the product name - the other answers make the mistake of using the class name.

This single file is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc or inherit from NSObject.

Considerations:

  • If your product name contains spaces, replace them with underscores (e.g. My Project becomes My_Project-Swift.h)

  • If your target is a framework, you need to import <ProductName/ProductName-Swift.h>

  • Make sure your Swift file is member of the target

Importing Project-Swift.h into a Objective-C class...file not found

I was running into the same issue and couldn't get my project to import swift into obj-c classes. Using Xcode 6, (should work for Xcode 6+) and was able to do it in this way....

  1. Any class that you need to access in the .h file needs to be a forward declaration like this

@class MySwiftClass;


  1. In the .m file ONLY, if the code is in the same project (module) then you need to import it with

#import "ProductModuleName-Swift.h"

Link to the apple documentation about it

https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_swift_into_objective-c

swift build errors from Objective-C app due to import of Objective-C static library that contains a .swift file

The simplest solution is to allow Xcode to make all dependencies and include all required system libs.

Here is what I did:

  1. Create workspace at top folder level

  2. Added mobile_sensor_API.xcodeproj to workspace

  3. Added sim_backend_UI.xcodeproj to workspace

  4. Added dependency of sim_backend_UI to lib via workspace

demo


  1. Add Some.swift (any swift file you want) to sim_backend_UI, just for the purpose Xcode add required system swift dynamic libraries (which will be needed for swift part in static library as well)... and confirm creating bridge in appeared dialog

demo2


  1. Build >>> Succeeded!

UPDATE 3 .................................. AFTER I DID THIS ANSWER thru step 6, I got "succeeded" but sim_backend_UI.app is RED and won't run on iphone.

Sample Image

Why can't I use my swift files in my objective-c code?

To clarify... Your class must be marked @objc and must derive from NSObject, and your func must also be marked @objc:

@objc class UserDefaultFactory: NSObject {
@objc func a() {
print("HELLO")
}
}

To then call that func from Objective-C code:

UserDefaultFactory *udf = [UserDefaultFactory new];
[udf a];

You could also call it via:

[[UserDefaultFactory new] a];

but more than likely you will be creating an instance of your UserDefaultFactory object for additional usage.



Related Topics



Leave a reply



Submit