xcode 如何在 Framework 目标中从 Objective-C 调用 Swift 代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36612880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:43:57  来源:igfitidea点击:

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

objective-cxcodeswift

提问by Gruntcakes

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/

当您将 Swift 文件添加到 Objective-C 项目时,Xcode 将生成一个 Swift-to-ObjC 标头,如下所述:http://ericasadun.com/2014/08/21/swift-calling-swift-functions-从目标-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.

如果没有这个头文件,就不可能从 Objc-C 调用 Swift 代码。但是,Xcode 不会为我的框架目标自动生成此标头。

If I create an Objective-C appand 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.

如果我创建一个 Objective-C应用程序并将一个 Swift 文件放入其中,那么它会自动生成一个,所以我怀疑这是因为我正在构建一个框架而不是一个应用程序。没有它就不可能使用 Obj-C 代码中的 Swift 代码。

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.

我尝试使用为应用程序生成的文件(在重命名并将其放入适当的 DerivedData 文件夹后),但 Xcode 没有更新它,实际上它最终会删除它,因此手动创建或尝试维护此文件不是可行的。

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?

如何让 Xcode 为框架目标生成此标头,以便我可以从我的 Obj-C 代码中调用我的 Swift 代码?

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

记住人们:问题是关于从 Obj-C 调用 Swift 而不是从 Swift 调用 Obj-C。

回答by jtbandes

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

我创建了一个新的框架项目,添加了 Obj-C 和 Swift 文件,并且能够做到这一点:

// 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:

请注意,您的 Swift 类必须是public

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

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

更多信息可在Apple 的 Swift/Obj-C 互操作文档中的“将 Swift 导入 Objective-C”下找到。