我尝试在我的应用程序中集成Swift代码。我的应用程序是用Objective-C编写的,我添加了一个Swift类。我做了这里描述的所有事情。但我的问题是Xcode还没有创建-Swift.h文件,只有桥接头。我创建了它,但它实际上是空的。 我可以在Swift中使用我所有的ObjC类,但我不能反之亦然。我用@objc标记了我的swift类,但它没有帮助。我现在该怎么办?

编辑:苹果说:“当你将Swift代码导入Objective-C时,你依靠xcode生成的头文件将这些文件公开给Objective-C。[…此头文件的名称是您的产品模块名称,后跟“-Swift.h”。

现在当我想导入这个文件时,它会给出一个错误:

    //MainMenu.m

    #import "myProjectModule-Swift.h" //Error: 'myProjectModule-Swift.h' file not found

    @implementation MainMenu

这是我的FBManager.swift文件:

@objc class FBManager: NSObject {

    var descr = "FBManager class"

    init() {
        super.init()
    }

    func desc(){
        println(descr)
    }

    func getSharedGameState() -> GameState{
        return GameState.sharedGameState() //OK! GameState is written in Objective-C and no error here
    }
}

当前回答

我刚刚发现,在项目中添加swift文件目录是行不通的。您需要首先为该目录创建一个组,然后添加swift文件…

其他回答

确保您的项目定义了一个模块,并为该模块指定了名称。然后重新构建,Xcode会创建-Swift.h头文件,你就可以导入了。

您可以在项目设置中设置模块定义和模块名称。

允许Xcode做它的工作,不要手动添加/创建Swift头。只需要在你的Swift类ex之前添加@objc。

@objc class YourSwiftClassName: UIViewController

在你的项目设置中搜索以下标志,并将其更改为YES(项目和目标)

Defines Module : YES
Always Embed Swift Standard Libraries : YES
Install Objective-C Compatibility Header : YES

然后清理项目并构建一次,在构建成功后(可能应该)在objective-c类.m文件中导入下面的头文件

#import "YourProjectName-Swift.h" 

嘭!

我不需要改变构建中的任何设置,也不需要将@obj添加到类中。

我所要做的就是创建bridge-header,当我在Objective-c项目中创建Swift类时,它会自动创建。然后我要做的就是

导入"Bedtime-Swift.h" <-需要使用swift文件的objective-c内部文件。

在做了以上所有事情之后,我仍然得到了错误。我的问题是我需要的Swift文件由于某种原因没有添加到bundle资源中。

我通过去[MyTarget] > Build Phases > Copy Bundle Resources修复了这个问题,然后单击加号按钮并添加Swift文件。

我花了大约4个小时试图在我的基于Xcode Objective-C的项目中启用Swift。我的myproject-Swift.h文件创建成功,但我的Xcode没有看到我的swift类。所以,我决定创建一个新的基于Xcode对象的项目,最后,我找到了正确的答案!希望这篇文章能帮助到一些人:-)

Step by Step Swift integration for Xcode object -based project:

Create new *.swift file (in Xcode) or add it by using Finder. Create an Objective-C bridging header when Xcode asks you about that. Implement your Swift class: import Foundation // use @objc or @objcMembers annotation if necessary class Foo { //.. } Open Build Settings and check these parameters: Defines Module : YES Copy & Paste parameter name in a search bar Product Module Name : myproject Make sure that your Product Module Name doesn't contain any special characters Install Objective-C Compatibility Header : YES Once you've added *.swift file to the project this property will appear in Build Settings Objective-C Generated Interface Header : myproject-Swift.h This header is auto-generated by Xcode Objective-C Bridging Header : $(SRCROOT)/myproject-Bridging-Header.h Import Swift interface header in your *.m file. #import "myproject-Swift.h" Don't pay attention to errors and warnings. Clean and rebuild your Xcode project. Profit!