ios - 不能在 Objective-C 中使用 Swift 类

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

编辑:Apple 说:“当您将 Swift 代码导入到 Objective-C 时,您依赖于 Xcode-generated 头文件将这些文件公开给 Objective-C。[...]此 header 的名称是您的产品模块名称,后跟“-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
    }
}

最佳答案

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

基于 Xcode Objc 的项目的逐步 Swift 集成:

  1. 创建新的 *.swift 文件(在 Xcode 中)或使用 Finder 添加它。
  2. 当 Xcode 询问您时,创建一个 Objective-C 桥接头
  3. 实现你的 Swift 类:

    import Foundation
    
    // use @objc or @objcMembers annotation if necessary
    class Foo {
        //..
    }
    
  4. 打开build设置并检查这些参数:

    • 定义模块: YES

      Copy & Paste parameter name in a search bar

    • 产品模块名称: myproject

      Make sure that your Product Module Name doesn't contain any special characters

    • 安装 Objective-C 兼容性头文件: YES

      Once you've added *.swift file to the project this property will appear in Build Settings

    • Objective-C 生成的接口(interface)头文件: myproject-Swift.h

      This header is auto-generated by Xcode

    • Objective-C 桥接头: $(SRCROOT)/myproject-Bridging-Header.h
  5. 在您的 *.m 文件中导入 Swift 接口(interface) header 。

    #import "myproject-Swift.h"
    

    Don't pay attention to errors and warnings.

  6. 清理并重建您的 Xcode 项目。
  7. 利润!

https://stackoverflow.com/questions/24206732/

相关文章:

ios - 检测设备是否为 iPhone X

iphone - 如何比较两个 NSDates : Which is more recent?

ios - 解释 iOS7 中自动调整 ScrollView 插入、扩展布局包含不透明条、边缘For

objective-c - 将 NSDate 转换为 NSString

iOS - 从 ViewController 调用 App Delegate 方法

ios - 总是将 self 的弱引用传递到 ARC 中的 block 中?

objective-c - UILabel中如何控制行距

ios - UIView无限360度旋转动画?

ios - 使用 Storyboard 以编程方式设置初始 View Controller

objective-c - 编译警告 : no rule to process file for a