我最近一直在努力将Swift添加到一个现有的项目中,以便在现实世界中进行尝试。

在向项目中添加Swift源文件时,我对获得“桥接头”没有任何问题,也就是说,Objective-C到Swift。

但是*-Swift.h头文件应该公开Swift类,无论是标记为@objc的类还是ObjC类的子类,都找不到:-(

在我的主应用程序代码(仍然是Objective-C)中,我没有看到任何关于如何使用我的新子类的具体说明,用Swift编写。

我是首席开发人员的应用程序有一个相当大的代码库(70.000行),所以一次性过渡它是不可能的。


当前回答

I had similar problem but my project was compiling before and suddenly got error after few files code change. It took me while to figure out why I am getting 'File not found' error for myproject-swift.h file. The code changes I had done had some errors. Xcode did not point put those error instead all time showing the 'File not found error'. Then got copy of previous version code and I compared with new code and merged file one by one. After each file merge complied the project to find the error. So bottom line is if you have error in your code Xcode may just display 'file not found error' for myproject-swift.h file. Most likely you have compilation error in your project. Clean those error and it will work.

其他回答

文件名的前面总是您的目标名称。它被称为产品名称,但实际上它是目标名称。 因此,如果你想为一个新目标构建它,准备好期待that_target-Swift.h文件。

一种处理方法是

为每个目标添加一个预处理器,它是目标本身的名称(不带空格)。MY_TARGET = 1。将此添加到项目设置->构建设置->预处理器宏为每个目标。 如果您正在使用PCH文件,

在PCH文件中添加这些行

#if MY_TARGET==1
#include "My_Target-Swift.h"
#elif THAT_TARGET==1
#include "That_Target-Swift.h" 
#endif

使用PCH文件的优点是您不必在任何地方都包含头文件。

如果您不使用PCH文件,只需在单个头文件中添加这些相同的行,并在需要使用swift类的任何地方包含该头文件。

这应该可以正常工作。

如果Xcode实际上生成了你的-Swift.h头(在DerivedData的深处),但它没有引用你的Swift类,请确保你也定义了一个桥接头。我阅读文档的方式暗示我只需要从Swift调用Objective-C,但似乎从Objective-C调用Swift也是必要的。

请看我的回答:https://stackoverflow.com/a/27972946/337392

编辑:这是因为公共和内部访问修改器,正如我最终在苹果文档中发现的解释:-

默认情况下,生成的头包含Swift接口 用公共修饰符标记的声明。它还包含了 如果你的应用目标有 Objective-C桥接头。

我找到了这个解决方案

创建SwiftBridge.h 导入" ProductModuleName-Swift.h " 将此.h文件公开(重要)选择该文件->在“显示文件检查器”中(右栏)->将其公开

现在你可以

#import "SwiftBridge.h"

而不是ProductModuleName-Swift.h

这是一个变通的解决方案,在下一个版本的Xcode中,我认为这个问题会得到解决。 祝你好运

唯一重要的是:*

在目标中使用定义的“产品模块名”,后跟-Swift.h

#import <Product Module Name>-Swift.h

// in each ObjectiveC .m file having to use swift classes
// no matter in which swift files these classes sit.

无论“定义模块”参数设置为“是”或“否”,或“产品模块名称”项目未设置。

提醒:Swift类必须派生自NSObject或被标记为@objc属性,以便暴露给ObjectiveC / Foundation || Cocoa…

我发现了一个对我很管用的小窍门。

Create your #import "ProductModuleName-Swift.h" in your appDelegate.h file and in your ProductName-Prefix.pch file. If you don't have it in xcode 6 you can create it with this way Why isn't ProjectName-Prefix.pch created automatically in Xcode 6? Command+shift+k to clean your code, if you receive an error about your "ProductModuleName-Swift.h" delete it from appDelegate.h file. Clean your code again. Now everything will work like a charm If you receive again error about the "ProductModuleName-Swift.h", now create again in appDelegate.h file and clean your code again.

每次你收到这个错误的时候都要做这个工作(从appDelegate.h文件中删除并创建“ProductModuleName-Swift.h”,然后清理你的代码)来静音它。