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

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

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

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

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


当前回答

这可能是一个明显的点(也许太明显了),但是您必须在项目中至少有一个swift文件来生成头文件。如果您正在编写样板或配置代码,意图稍后编写swift,则导入将不起作用。

其他回答

最重要的是这个文件是不可见的!!至少在Xcode6 beta5中是这样的。在您的工作空间中不会有这样一个名为“YourModule-Swift.h”的文件。只需确保模块名称和定义模块设置为yes,并在Objective-C类中使用它。

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.

附议很多人在这里,但增加一个相关的屏幕截图。Swift和Obj-C代码当然可以共存。这不是全有或全无的游戏。

要在Objective-C中访问Swift文件,你所需要做的就是将这个调用添加到你的Obj-C文件中(在.m /实现文件中):

#import "{product_module_name}-Swift.h"

(其中{product_module_name}表示项目的产品模块名称)。而不是尝试猜测你的产品模块名称或找出带有空格和特殊字符的角落案例,只需进入项目中的构建设置选项卡并键入“产品模块名称”-检查器将显示给你。我的经历是我没有预料到的。如果你感到困惑,可以看看这个屏幕截图。

为了让Obj-c代码在Swift中工作,你只需要添加一个桥接头文件,并导入相关的Obj-c头文件。

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

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”,然后清理你的代码)来静音它。

唯一重要的是:*

在目标中使用定义的“产品模块名”,后跟-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…