ios - 将 Swift 导入 Objective-C - "use of undeclared identifier"

标签 ios objective-c swift xcode

我无法将 Swift 类导入 Objective-C。

  • Xcode 版本:10.1
  • swift :4.2

我的步骤:

  1. 创建名为“test”的空单 View Objective-C 项目。

  2. 创建 Swift 类 (mytestclass.swift)

  3. 创建桥接空头“test-Swift.h”

  4. 尝试像这样在 ViewController.m 中使用:#import "test-Swift.h" [[MyTestClass init] 计算];

我的测试类.swift

import Foundation

@objc public class MyTestClass: NSObject {

    @objc public func calculate() {
        print("TEST")
    }
}

编译后得到:

/Users/xxx/Desktop/test/ViewController.m:19:7: Use of undeclared identifier 'MyTestClass'

我错过了什么?

最佳答案

你的问题在步骤

3- Create bridging empty header "test-Swift.h"

您不应该手动创建该文件,因为它是在您将 swift 文件添加到您的 Objective-C 时创建的,您还需要替换这一行

[[MyTestClass init] calculate];

[[[MyTestClass alloc] init] calculate];

[[MyTestClass new] calculate];

这是一个有效的 demo

关于ios - 将 Swift 导入 Objective-C - "use of undeclared identifier",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54181884/

相关文章:

iphone - 逻辑单元测试崩溃

ios - 今天使用 SpriteKit 的扩展

objective-c - Mac OS X XPC 作为两个应用程序之间的 IPC

ios - 如何在日志中输出 CAF 文件大小?

swift - Swift 项目中的 C++ dylib - dylib 中公开的函数的 undefined symbol

ios - Xcode Swift sprite-kit SKS 文件动画在 SKS 文件中正常工作,但在模拟器或 iPhone 上不起作用

ios - 让 invokeUndefinedMethodFromWebScript 在 Swift 中工作

ios - 如何更改多个 IBOutlet 的属性

ios - 不确定如何设置 View 对象并连接 IBOutlet 代码

iOS 9.2.1 无法在设备设置中看到设置包