# @arrirpc/codegen-swift 中文文档

规范地址：https://npmcn.com/package/%40arrirpc/codegen-swift/

版本：0\.85\.0
npm 元数据更新时间：2026-10-03T04:04:00.948Z
中文译文更新时间：2026-11-06T20:22:36.838Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40arrirpc/codegen-swift
原文对照：https://npmcn.com/package/%40arrirpc/codegen-swift/?lang=original
项目主页：https://github.com/modiimedia/arri#readme
源码仓库：https://github.com/modiimedia/arri

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：116 kB，8 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2024-08-17T03:34:06.939Z
- 最新版本发布：2026-10-03T04:04:00.763Z
- 近 30 天下载量：4567（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：56（近 12 个月 11 个）

## 中文简介

请注意:生成的代码尚不支持 `swift-tools-version 6` 或超过。 请跟踪这个问题的状况 [这里](https://github.com/modiimedia/arri/issues/167)同时请设置您的 `swift-tools-version` 改为 `5.10` 或低于

## 安装

```sh
npm install @arrirpc/codegen-swift
```

也可以使用：`pnpm add @arrirpc/codegen-swift`、`yarn add @arrirpc/codegen-swift`、`bun add @arrirpc/codegen-swift`

## README

# 阿里·斯威夫特编码

_请注意: 生成的代码尚不支持 `swift-tools-version 6` 或超过。 请跟踪这个问题的状况 [这里](https://github.com/modiimedia/arri/issues/167)同时请设置您的 `swift-tools-version` 改为 `5.10` 或低一点._

## 设置

### 1) 将 Swift 客户端生成器添加到您的 arri 配置

```ts
// arri.config.ts
import { defineConfig, generators } from 'arri';

export default defineConfig({
    generators: [
        generators.swiftClient({
            clientName: 'MyClient',
            outputFile: './client/Sources/MyClient.g.swift',
        }),
    ],
});
```

**选项 :**

| 名称 | 说明 |
| --- | --- |
| 输出文件( 需要) | 由生成器创建的文件路径 |
| 客户端Name | 生成客户端的名称 |
| 类型 前缀 | 在所有生成类型中添加前缀 |
| 根服务 | 生成客户端的根服务 |

### (2) 安装 Swift 客户端库

生成的代码依赖于 [阿里·斯威夫特客户端](https://npmcn.com/languages/swift/swift-client) 图书馆,请务必把它添加到你的快速项目中。 版本号应该与您的 Arri CLI 版本相匹配 .

#### Swift 软件包管理器

添加数据 `arri-client-swift` git repo 到您的软件包依赖度

```swift
.package(
    url: "https://github.com/modiimedia/arri-client-swift.git",
    from: "<your-arri-cli-version>"
)
```

然后添加 `ArriClient` 作为你的目标的依赖

```swift
.target(
    name: "MyApp",
    dependencies: [
        .product(name: "ArriClient", package: "arri-client-swift")
    ]
)
```

## 使用生成代码

### 初始化客户端

```swift

let client = MyClient(
    baseURL: "https://example.com",
    delegate: DefaultRequestDelegate(),
    headers: {
        var headers: Dictionary<String, String> = Dictionary()
        return headers
    },
    // optional
    onError: { err in
        // do something
    }
)

await client.myProcedure()
```

根客户端将是一个包含所有子服务和程序的结构. 如果你只需要特殊服务,你可以初始化服务.

例如,如果我们将一些程序归类于以下: `"users"` 我们可以像这样初始化用户服务.

```swift
let usersService = MyClientUsersService(
    baseURL: "https://example.com",
    delegate: DefaultRequestDelegate(),
    headers: {
        var headers: Dictionary<String, String> = Dictionary()
        return headers
    }
)

usersService.someProcedure()
```

### 使用生成类型

所有产生的结构、班级和有标签的工会都执行 `ArriClientModel` 协议,它看起来像:

```swift
public protocol ArriClientModel: Equatable {
    init()
    init(json: JSON)
    init(JSONString: String)
    func toJSONString() -> String
    func toURLQueryParts() -> [URLQueryItem]
    func clone() -> Self
}
```

所有生成的标准enums执行 `ArriClientEnum` 协议,它看起来像:

```swift
public protocol ArriClientEnum: Equatable {
    init()
    init(serialValue: String)
    func serialValue() -> String
}
```

### 调用事件流程序

程序生成a [任务](https://developer.apple.com/documentation/swift/task)

```swift
var msgCount = 0
var openCount = 0
let params = WatchUserParams()

// event stream procedures return a task that you can cancel whenever
let task: Task<(), Never> = client.users.watchUser(
    params,
    options: EventSourceOptions(
        onMessage: { msg, eventSource in
            msgCount += 1
            print("New message: \(msg)")
        },
        onRequest: nil,
        onRequestError: nil,
        onResponse: { _, eventSource in
            openCount += 1
            print("Established connection!")
        },
        onResponseError: { err, eventSource in
            print("The server returned an error: \(err)")
            // you can also cancel the task from inside one of these hooks
            // by calling `cancel()` on the EventSource.
            // this will cause the parent Task to be completed
            eventSource.cancel()
        },
        onClose: nil,
        maxRetryCount: nil,
        maxRetryInterval: nil,
    )
)

// if you want to wait for the task to finished
await task.result
// this will continue indefinitely unless the server sends a "done" event
// or you call `cancel()` on the EventSource
```

#### 可用事件源选项

-   `onMessage` - 一旦从服务器收到"消息"事件,即关闭发射装置。 这是唯一必要的选择.
-   `onRequest` - 当一项请求已经提出但尚未执行时,关闭该请求.
-   `onRequestError` - 关闭在创建请求时发生错误(即错误的URL),或者无法连接到服务器时点火。 (即: `connectionRefused` 错误)
-   `onResponse` - 当我们收到服务器的回复时关闭起火器
-   `onResponseError` - 关闭服务器未使用状态代码进行响应时起火 `200` - 说吧 `299` 或 `Content-Type` 页眉不包含 `text/event-stream`
-   `onClose` - 当事件源被关闭时关闭火灾。 (这只有在事件源代码已经能够成功收到服务器的响应时才会开火. )
-   `maxRetryCount` - 限制事件源试图重新连接到服务器的次数。 设定为 `nil` 它将无限期地重试。 (过失是) `nil`(中文(简体) )
-   `maxRetryInterval` - 设定每毫秒重试之间的最大延迟时间。 默认是 `30000`。 。 。 .

## 补充说明

目前 `DefaultRequestDelegate()` 依赖 [AsyncHTTPC 键](https://github.com/swift-server/async-http-client). 我想最终去除这种依赖,所以如果有人知道如何让服务器发送事件(Server Sent Events)与斯威夫特基金会图书馆合作,请打开一个问题. 请注意,这些客户端需要运行Linux,所以拟议解决方案需要工作而不使用 `URLSession.asyncBytes` 或其他任何只在苹果平台工作的API.

## 常见问题

### @arrirpc/codegen-swift 是什么？

请注意:生成的代码尚不支持 swift-tools-version 6 或超过。 请跟踪这个问题的状况 这里同时请设置您的 swift-tools-version 改为 5\.10 或低于

### 如何安装 @arrirpc/codegen-swift？

在项目目录运行 npm install @arrirpc/codegen-swift，或使用 pnpm add / yarn add / bun add。

### @arrirpc/codegen-swift 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @arrirpc/codegen-swift 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @arrirpc/codegen-swift 可以商用吗？

@arrirpc/codegen-swift 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @arrirpc/codegen-swift 的下载量有多少？

根据 npm 官方下载统计，@arrirpc/codegen-swift 在 2026/10/07 – 2026/11/05 这 30 天内被下载 4,567 次，日均约 152 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @arrirpc/codegen-swift 还在维护吗？

最新版本 0\.85\.0 发布于 2026/10/03（1 个月前）；至今共发布 56 个版本，其中过去 12 个月发布了 11 个；首次发布于 2024/08/17。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

