Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Swift classes within a Objective-C Framework

I have a custom Framework that has a bunch of Objective-C Classes. Within the Framework, I'd like to add more classes using Swift. However, when trying to expose the Swift classes to the Objective-C code using: MyProduct-Swift.h, it comes up as "MyProduct-Swift.h file not found".

I've tried this in a single view template and it works fine. Is it not possible to import Swift within a framework?

I've also verified that I have set the Defines Module setting and the Module Name. I've tried it with and without these settings.

like image 322
Oxcug Avatar asked Jun 09 '14 21:06

Oxcug


People also ask

How do I import a Swift class into Objective-C?

Import Swift code into Objective-C within the same framework: Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .

How do you inherit a Swift class in Objective-C?

Swift classes that are inherited from OBJC classes are bridged automatically. That means any class inherited from, for example, UIViewController is automatically seen in the OBJC runtime. If you're creating a class that doesn't inherit from anything, then make it an NSObject subclass, as you would in OBJC.

Can you use Swift and Objective-C together?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

Does Apple use Swift or Objective-C?

Most of the core iOS and MacOs software is still written in Objective-C, though Apple is pushing for new updates to be written in Swift.


2 Answers

I found some additional steps to make it all work. In addition to setting 'Define Module' to YES and 'Product Module Name' (usually these are set correct by default if you create new touch Framework in Xcode 6) you also need:

  1. add 'public' keyword to all Swift classes you need in Objective C
  2. you need to add 'public' keyword even to all the methods and properties within the class that you want to access from Objective C
  3. You need to import Swift header in a 'long' way like this:

#import <ProjectName/ModuleName-Swift.h>

like image 177
Matej Ukmar Avatar answered Oct 20 '22 04:10

Matej Ukmar


Ok, I found what the problem is.

Make sure that in Build Settings - > Packaging you have Define Module set to YES and Product Module Name is set as well. Then in the storyboard file the name for the Module should be the same and match what you have in your Build Settings. Then in your Obj-C file write include "-Swift.h"

That did the trick for me.

like image 39
Irina Avatar answered Oct 20 '22 04:10

Irina