swift_combine
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwift Combine
Swift Combine
This skill covers Apple's Combine framework for reactive programming and handling asynchronous events.
本技能涵盖了苹果用于响应式编程和处理异步事件的Combine框架。
Overview
概述
Combine is a declarative Swift API for processing values over time. It provides a unified approach to handling asynchronous events, user interface updates, and data streams.
Combine是一个用于随时间处理值的声明式Swift API。它提供了统一的方式来处理异步事件、用户界面更新和数据流。
Available References
可用参考资料
- Publishers & Subscribers - Core concepts and lifecycle
- Operators - Transforming, filtering, and combining streams
- Integration - Using Combine with UIKit, SwiftUI, and Foundation
- 发布者与订阅者 - 核心概念与生命周期
- 操作符 - 转换、过滤和组合数据流
- 集成 - 在UIKit、SwiftUI和Foundation中使用Combine
Quick Reference
快速参考
Basic Publisher
基础发布者
swift
import Combine
// Published property
@Published var username: String = ""
// CurrentValueSubject
let subject = CurrentValueSubject<String, Never>("initial")
// PassthroughSubject
let passthrough = PassthroughSubject<Int, Never>()
// Just publisher
let just = Just("value")
// Future publisher
let future = Future<String, Error> { promise in
promise(.success("result"))
}swift
import Combine
// Published属性
@Published var username: String = ""
// CurrentValueSubject
let subject = CurrentValueSubject<String, Never>("initial")
// PassthroughSubject
let passthrough = PassthroughSubject<Int, Never>()
// Just发布者
let just = Just("value")
// Future发布者
let future = Future<String, Error> { promise in
promise(.success("result"))
}Subscribing
订阅
swift
// Sink
let cancellable = publisher.sink(
receiveCompletion: { completion in
switch completion {
case .finished:
print("Completed")
case .failure(let error):
print("Error: \(error)")
}
},
receiveValue: { value in
print("Value: \(value)")
}
)
// Assign
let cancellable = publisher
.assign(to: \.text, on: label)swift
// Sink
let cancellable = publisher.sink(
receiveCompletion: { completion in
switch completion {
case .finished:
print("Completed")
case .failure(let error):
print("Error: \(error)")
}
},
receiveValue: { value in
print("Value: \(value)")
}
)
// Assign
let cancellable = publisher
.assign(to: \.text, on: label)Storing Subscriptions
存储订阅
swift
private var cancellables = Set<AnyCancellable>()
publisher
.sink { value in
print(value)
}
.store(in: &cancellables)swift
private var cancellables = Set<AnyCancellable>()
publisher
.sink { value in
print(value)
}
.store(in: &cancellables)Common Operators
常用操作符
swift
publisher
.filter { $0 > 0 }
.map { $0 * 2 }
.debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.removeDuplicates()
.sink { value in
print(value)
}swift
publisher
.filter { $0 > 0 }
.map { $0 * 2 }
.debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.removeDuplicates()
.sink { value in
print(value)
}Combine vs Async/Await
Combine vs Async/Await
| Use Case | Combine | Async/Await |
|---|---|---|
| Event streams | ✅ Excellent | ⚠️ Complex |
| UI bindings | ✅ Perfect | ⚠️ Verbose |
| Chaining operations | ✅ Great | ✅ Good |
| Simple async calls | ⚠️ Overkill | ✅ Simple |
| Error handling | ✅ Rich | ✅ Good |
| 使用场景 | Combine | Async/Await |
|---|---|---|
| 事件流 | ✅ 出色 | ⚠️ 复杂 |
| UI绑定 | ✅ 完美 | ⚠️ 繁琐 |
| 链式操作 | ✅ 优秀 | ✅ 良好 |
| 简单异步调用 | ⚠️ 大材小用 | ✅ 简单 |
| 错误处理 | ✅ 丰富 | ✅ 良好 |
Best Practices
最佳实践
- Store cancellables - Prevent memory leaks
- Use weak self - Avoid retain cycles
- Handle errors - Always handle completion
- Thread safety - Use receive(on:) for UI
- Cancel properly - Clean up subscriptions
- Avoid overuse - Combine is powerful but not for everything
- Test pipelines - Use expectations for async
- 存储cancellables - 防止内存泄漏
- 使用weak self - 避免循环引用
- 处理错误 - 始终处理完成事件
- 线程安全 - 对UI使用receive(on:)
- 正确取消 - 清理订阅
- 避免过度使用 - Combine功能强大,但并非适用于所有场景
- 测试流水线 - 使用期望测试异步操作
For More Information
更多信息
Visit https://swiftzilla.dev for comprehensive Combine documentation.
访问 https://swiftzilla.dev 获取全面的Combine文档。