混用Swift和objc - 共存于一个工程

Importing Code from Within the Same App Target

将 objc 导入 Swift

要在同一个 app 中将 objc 文件导入 Swift 代码,需要依赖于Objective-C bridging header将那些文件暴露给 Swift。当你在 objc 项目中新建 Swift 文件或在 Swift 项目中新建 oc 文件时,Xcode 会询问你是否要创建这类头文件。

如果选择接受,Xcode 会自动创建桥接头文件,名称为你的产品模块名加上"-Bridging-Header.h"。当然你也可以自己手动创建桥接头文件。

需要编辑桥接头文件来将 objc 代码暴露给 Swift。

从同一个 target 中将 objc 代码导入 Swift

  1. 在 objc 桥接头文件中,导入每个你想要暴露给 Swift 的 objc 头文件:
1
2
3
#import "XYZCustomCell.h"
#import "XYZCustomView.h"
#import "XYZCustomViewController.h"
  1. 在 Build Setting 中,在 Swift Compiler - Code Generation,保证 Objective-C Bridging Header 设置项有访问桥接头文件的路径。这个路径是相对于工程的路径,一般情况下不需要修改。

所有写在桥接头文件中的公共 objc 头文件都对 Swift 可见。不用 import 语句,在这个 target 中,任何 Swift 文件都能使用这些可见的 objc。

1
2
let myCell = XYZCustomCell()
myCell.subtitle = "A custom cell"

将 Swift 导入 objc

将 Swift 导入 objc 也需要一个头文件,这个文件是自动生成的——产品模块名加上"-Swift.h"

默认的,这个文件包含 Swift 中被标记为publicopen的接口。如果你的 app target 有 objc 桥接文件,它也包含标记为internal的接口。这个文件不包含privatefileprivate接口。私有声明不会暴露给 objc 除非它们显示标记为@IBAction@IBOutlet@objc。为了让测试 target 访问interval的声明,可以在产品模块导入前加上@testable

生成的头文件只要在 objc 文件中导入就行了,其他不用做什么。Note that the Swift interfaces in the generated header include references to all of the Objective-C types used in them. If you use your own Objective-C types in your Swift code, make sure to import the Objective-C headers for those types before importing the Swift generated header into the Objective-C .m file you want to access the Swift code from.

从同一个 target 中将 Swift 代码导入 objc

1
#import "ProductModuleName-Swift.h"

包含这条导入语句的 objc 文件都能访问 target 中的 Swift 代码。

Import into Swift Import into Objective-C
Swift code No import statement #import “ProductModuleName-Swift.h”
Objective-C code No import statement; Objective-C bridging header required #import “Header.h”

Importing Code from Within the Same Framework Target

方法与上一节基本相同。

Import into Swift Import into Objective-C
Swift code No import statement #import <ProductName/ProductModuleName-Swift.h>
Objective-C code No import statement; Objective-C umbrella header required #import “Header.h”

参考