Swift Async Algorithms 中的异步序列类型擦除技术解析
2025-06-25 08:18:56作者:柏廷章Berta
异步序列类型擦除的背景
在 Swift 并发编程中,AsyncSequence 是一个非常重要的协议,它允许我们以异步方式处理序列数据。然而,当我们需要组合多个 AsyncSequence 时,返回类型往往会变得非常复杂且难以维护。
问题现状
当前 Swift 5.x 版本中,当我们合并两个来自 NotificationCenter 的异步通知序列时,会遇到两个主要问题:
- 返回类型过于复杂,包含多层嵌套的泛型类型
- 在严格并发检查模式下会出现 Sendable 相关的警告
例如,合并两个通知序列的返回类型可能看起来像这样:
AsyncMerge2Sequence<AsyncMapSequence<NotificationCenter.Notifications, Notification.Name>, AsyncMapSequence<NotificationCenter.Notifications, Notification.Name>>
临时解决方案
在 Swift 6.0 发布之前,我们可以采用以下两种临时解决方案:
1. 使用 AnyAsyncSequence 包装器
创建一个类型擦除的包装器,可以隐藏底层复杂的类型信息。这种方案的优点是保持了异步序列的原始特性,包括背压传播等机制。
struct AnyAsyncSequence<Element>: AsyncSequence {
typealias AsyncIterator = AnyAsyncIterator<Element>
typealias Element = Element
private let _makeAsyncIterator: () -> AnyAsyncIterator<Element>
init<S: AsyncSequence>(_ sequence: S) where S.Element == Element {
_makeAsyncIterator = {
AnyAsyncIterator(sequence.makeAsyncIterator())
}
}
func makeAsyncIterator() -> AnyAsyncIterator<Element> {
_makeAsyncIterator()
}
}
2. 使用 AsyncStream 转换
虽然不推荐,但在性能要求不高的情况下,可以将 AsyncSequence 转换为 AsyncStream。需要注意的是,这种方法会破坏背压机制,可能导致内存问题。
extension NotificationCenter {
private func typeErasedNotifications(_ name: Notification.Name) -> AsyncStream<Notification.Name> {
AsyncStream { continuation in
let task = Task {
for await notification in self.notifications(named: name) {
continuation.yield(notification.name)
}
}
continuation.onTermination = { _ in task.cancel() }
}
}
}
Swift 6.0 的改进
Swift 6.0 将通过 SE-0421 引入更优雅的解决方案。新特性允许我们使用更简洁的语法来表达异步序列类型:
some AsyncSequence<Notification, any Error>
或者对于不会抛出错误的序列:
some AsyncSequence<Notification, Never>
这种语法不仅更简洁,还能更好地表达异步序列的语义,是未来推荐的使用方式。
最佳实践建议
- 如果项目可以等待,建议升级到 Swift 6.0 后使用原生支持
- 当前版本推荐使用类型擦除包装器而非 AsyncStream 转换
- 注意保持背压机制,避免无限制缓冲数据
- 在严格并发模式下,确保相关类型符合 Sendable 协议
通过理解这些技术细节,开发者可以更优雅地处理复杂的异步序列组合场景,写出更健壮、更易维护的并发代码。
登录后查看全文
热门项目推荐
相关项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0223
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0142
uni-appA cross-platform framework using Vue.jsJavaScript09
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook04
热门内容推荐
最新内容推荐
项目优选
收起
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
470
467
deepin linux kernel
C
32
16
暂无描述
Dockerfile
781
5.09 K
Ascend Extension for PyTorch
Python
759
969
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
703
1.41 K
Claude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed.
Get Started
Rust
2.12 K
222
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
885
2.03 K
本仓库是 Flutter SDK 与 Flutter Engine 的 OpenHarmony 适配版本,由 CPF-Flutter 团队维护。开发者可使用熟悉的 Flutter 技术栈开发 OpenHarmony 应用,3.35.7 及以后的适配版本可基于本仓库源码构建支持 OpenHarmony 的 Flutter Engine。
Dart
1.04 K
272
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
C
462
5.48 K
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.1 K
1.15 K