# 07.OC项目中加入Swift混编

> 年后项目准备引入 `Swift` 新的模块需求使用 `Swift` 编写 需要支持与 `OC` 与 `Swift` 的混编 这里描述一下前期准备的工作

## Project\_defines module 配置

![](http://ohfpqyfi7.bkt.clouddn.com/15167571775287.jpg)

## Project\_product module name 配置

这里的 `Product Module Name` 需要和 `工程名称` 一致

![](http://ohfpqyfi7.bkt.clouddn.com/15167572476625.jpg)

## 代码修改

### 在需要调用到 `Swift` 的地方 `import`

```swift
#import "工程名称-Swift.h"
```

#### 注意点

* 这个文件 `import` 不会自动提示
* 而且如果项目汇总没有 `swift` 文件的话编译也会报错
* 不要自己去创建这个名字的文件
* 只需要在项目中创建一个 `Swift` 文件这个文件就会自动生成

### 需要暴露给 `Swift` 调用的

在 `OC` 项目中创建 `swift` 文件后会创建一个桥接文件 `工程名-Bridging-Header.h` 所有需要暴露给 `swift` 调用的文件都在这里 `import` 即可

#### 注意点

* 需要注意的是: 如果 `import` 的 `.h` 中有用到 `全局导入的引用` 时,编译会报错,这时需要在该被 `import` 的 `.h` 文件中添加相关引用或者使用 `@class` 即可
* 项目中的 `Swift` 文件中使用上面 `import` 过的 `OC类` 无须再单独 `import`
* 如果在添加到桥接文件中后某些类型依旧报错 可以尝试将其在桥接文件中的位置提前

## Apple官方混编指南

<https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID122>

## 国内汉化

<https://github.com/CocoaChina-editors/Welcome-to-Swift/blob/master/UsingSwiftwithCocoaandObjective-C中文手册.md>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/swift/oc-xiang-mu-zhong-jia-ru-swift-hun-bian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
