Scrungepipes
Scrungepipes

Reputation: 37590

How do I call Swift code from Objective-C in a Framework target?

When you add a Swift file to an Objective-C project, Xcode will generate a Swift-to-ObjC header, as described here: http://ericasadun.com/2014/08/21/swift-calling-swift-functions-from-objective-c/

Without this header it is not possible to call Swift code from Objc-C. However Xcode is not auto-generating this header for my framework target.

If I create an Objective-C app and drop a Swift file into it, then it does auto-generate one, so I suspect it's because I'm building a framework and not an app. Without one its not possible to use the Swift code from the Obj-C code.

I tried using the one which was generated for the app (after renaming it and putting it in the appropriate DerivedData folder ) but Xcode didn't update it and actually it will eventually delete it, so manually creating or trying to maintain this file is not feasible.

How can I make Xcode generate this header for a framework target, so that I can call my Swift code from my Obj-C code?

And remember folks: the question is about calling Swift from Obj-C not calling Obj-C from Swift.

Upvotes: 5

Views: 6549

Answers (2)

Shawn
Shawn

Reputation: 1

#import <MyFramework/MyFramework-Swift.h>

ATTENTION: this header file is generated auto!!!! Don't create it manually!!

Upvotes: -2

jtbandes
jtbandes

Reputation: 118751

I created a new Framework project, added both Obj-C and Swift files, and was able to do this:

// MyObjCClass.m

#import "MyObjCClass.h"
#import <MyFramework/MyFramework-Swift.h>

@implementation MyObjCClass
- (void)test {
    [[MySwiftClass alloc] init];
}
@end

Note that your Swift class must be public:

public class MySwiftClass: NSObject {
    // ...
}

More information is available in Apple's Swift/Obj-C interop documentation under "Importing Swift into Objective-C".

Upvotes: 12

Related Questions