swift-concurrency-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReview Swift concurrency code for correctness, modern API usage, and adherence to project conventions. Report only genuine problems - do not nitpick or invent issues.
Review process:
- Scan for known-dangerous patterns using to prioritize what to inspect.
references/hotspots.md - Check for recent Swift 6.2 concurrency behavior using .
references/new-features.md - Validate actor usage for reentrancy and isolation correctness using .
references/actors.md - Ensure structured concurrency is preferred over unstructured where appropriate using .
references/structured.md - Check unstructured task usage for correctness using .
references/unstructured.md - Verify cancellation is handled correctly using .
references/cancellation.md - Validate async stream and continuation usage using .
references/async-streams.md - Check bridging code between sync and async worlds using .
references/bridging.md - Review any legacy concurrency migrations using .
references/interop.md - Cross-check against common failure modes using .
references/bug-patterns.md - If the project has strict-concurrency errors, map diagnostics to fixes using .
references/diagnostics.md - If reviewing tests, check async test patterns using .
references/testing.md
If doing a partial review, load only the relevant reference files.
审查Swift并发代码的正确性、现代API使用情况以及是否符合项目规范。仅报告真实存在的问题——不要吹毛求疵或捏造问题。
审查流程:
- 使用扫描已知危险模式,确定优先检查的内容。
references/hotspots.md - 参考检查Swift 6.2的最新并发行为。
references/new-features.md - 使用验证Actor的可重入性和隔离正确性。
references/actors.md - 根据实际情况,优先选择结构化并发而非非结构化并发,参考。
references/structured.md - 使用检查非结构化任务的使用正确性。
references/unstructured.md - 使用验证取消操作是否处理正确。
references/cancellation.md - 使用验证异步流和continuation的使用。
references/async-streams.md - 使用检查同步与异步代码之间的桥接逻辑。
references/bridging.md - 参考审查任何遗留并发代码的迁移情况。
references/interop.md - 使用交叉检查常见故障模式。
references/bug-patterns.md - 如果项目存在严格并发错误,参考将诊断信息映射到修复方案。
references/diagnostics.md - 如果审查测试代码,参考检查异步测试模式。
references/testing.md
如果是部分审查,仅加载相关的参考文件。
Core Instructions
核心说明
- Target Swift 6.2 or later with strict concurrency checking.
- If code spans multiple targets or packages, compare their concurrency build settings before assuming behavior should match.
- Prefer structured concurrency (task groups) over unstructured ().
Task {} - Prefer Swift concurrency over Grand Central Dispatch for new code. GCD is still acceptable in low-level code, framework interop, or performance-critical synchronous work where queues and locks are the right tool – don't flag these as errors.
- If an API offers both /
asyncand closure-based variants, always preferawait/async.await - Do not introduce third-party concurrency frameworks without asking first.
- Do not suggest to fix compiler errors. It silences the diagnostic without fixing the underlying race. Prefer actors, value types, or
@unchecked Sendableparameters instead. The only legitimate use is for types with internal locking that are provably thread-safe.sending
- 目标为Swift 6.2或更高版本,并启用严格并发检查。
- 如果代码跨多个目标或包,在假设行为应一致之前,先比较它们的并发构建设置。
- 优先使用结构化并发(任务组)而非非结构化并发()。
Task {} - 新代码优先使用Swift并发而非Grand Central Dispatch。在底层代码、框架互操作或性能关键的同步工作中,队列和锁是合适工具的情况下,GCD仍然可以接受——不要将这些标记为错误。
- 如果某个API同时提供/
async和基于闭包的变体,始终优先选择await/async。await - 未经许可,不要引入第三方并发框架。
- 不要建议使用来修复编译器错误。这会掩盖诊断信息但不会修复潜在的竞态条件。优先选择Actor、值类型或
@unchecked Sendable参数。唯一合理的使用场景是具有内部锁且可证明线程安全的类型。sending
Output Format
输出格式
Organize findings by file. For each issue:
- State the file and relevant line(s).
- Name the rule being violated.
- Show a brief before/after code fix.
Skip files with no issues. End with a prioritized summary of the most impactful changes to make first.
Example output:
按文件整理发现的问题。对于每个问题:
- 说明文件和相关行号。
- 指出违反的规则。
- 展示简短的修复前后代码对比。
跳过没有问题的文件。最后给出按优先级排序的最具影响的修改总结。
示例输出:
DataLoader.swift
DataLoader.swift
Line 18: Actor reentrancy – state may have changed across the .
awaitswift
// Before
actor Cache {
var items: [String: Data] = [:]
func fetch(_ key: String) async throws -> Data {
if items[key] == nil {
items[key] = try await download(key)
}
return items[key]!
}
}
// After
actor Cache {
var items: [String: Data] = [:]
func fetch(_ key: String) async throws -> Data {
if let existing = items[key] { return existing }
let data = try await download(key)
items[key] = data
return data
}
}Line 34: Use instead of creating tasks in a loop.
withTaskGroupswift
// Before
for url in urls {
Task { try await fetch(url) }
}
// After
try await withThrowingTaskGroup(of: Data.self) { group in
for url in urls {
group.addTask { try await fetch(url) }
}
for try await result in group {
process(result)
}
}第18行:Actor可重入性——期间状态可能已更改。
awaitswift
// Before
actor Cache {
var items: [String: Data] = [:]
func fetch(_ key: String) async throws -> Data {
if items[key] == nil {
items[key] = try await download(key)
}
return items[key]!
}
}
// After
actor Cache {
var items: [String: Data] = [:]
func fetch(_ key: String) async throws -> Data {
if let existing = items[key] { return existing }
let data = try await download(key)
items[key] = data
return data
}
}第34行:使用替代在循环中创建任务。
withTaskGroupswift
// Before
for url in urls {
Task { try await fetch(url) }
}
// After
try await withThrowingTaskGroup(of: Data.self) { group in
for url in urls {
group.addTask { try await fetch(url) }
}
for try await result in group {
process(result)
}
}Summary
总结
- Correctness (high): Actor reentrancy bug on line 18 may cause duplicate downloads and a force-unwrap crash.
- Structure (medium): Unstructured tasks in loop on line 34 lose cancellation propagation.
End of example.
- 正确性(高优先级): 第18行的Actor可重入漏洞可能导致重复下载和强制解包崩溃。
- 结构(中优先级): 第34行循环中的非结构化任务会丢失取消传播。
示例结束。
References
参考资料
- - Grep targets for code review: known-dangerous patterns and what to check for each.
references/hotspots.md - - Swift 6.2 changes that alter review advice: default actor isolation, isolated conformances, caller-actor async behavior,
references/new-features.md,@concurrent, task naming, and priority escalation.Task.immediate - - Actor reentrancy, shared-state annotations, global actor inference, and isolation patterns.
references/actors.md - - Task groups over loops, discarding task groups, concurrency limits.
references/structured.md - - Task vs Task.detached, when Task {} is a code smell.
references/unstructured.md - - Cancellation propagation, cooperative checking, broken cancellation patterns.
references/cancellation.md - - AsyncStream factory, continuation lifecycle, back-pressure.
references/async-streams.md - - Checked continuations, wrapping legacy APIs,
references/bridging.md.@unchecked Sendable - - Migrating from GCD,
references/interop.md/locks, completion handlers, delegates, and Combine.Mutex - - Common concurrency failure modes and their fixes.
references/bug-patterns.md - - Strict-concurrency compiler errors, protocol conformance fixes, and likely remedies.
references/diagnostics.md - - Async test strategy with Swift Testing, race detection, avoiding timing-based tests.
references/testing.md
- - 代码审查的 grep 目标:已知危险模式及每种模式的检查要点。
references/hotspots.md - - 改变审查建议的Swift 6.2变更:默认Actor隔离、隔离一致性、调用方Actor异步行为、
references/new-features.md、@concurrent、任务命名和优先级提升。Task.immediate - - Actor可重入性、共享状态注解、全局Actor推断和隔离模式。
references/actors.md - - 用任务组替代循环、丢弃任务组、并发限制。
references/structured.md - - Task与Task.detached的区别,
references/unstructured.md何时是代码异味。Task {} - - 取消传播、协作式检查、存在问题的取消模式。
references/cancellation.md - - AsyncStream工厂、continuation生命周期、背压。
references/async-streams.md - - 受检continuation、包装遗留API、
references/bridging.md。@unchecked Sendable - - 从GCD迁移、
references/interop.md/锁、完成处理器、委托和Combine。Mutex - - 常见并发故障模式及其修复方案。
references/bug-patterns.md - - 严格并发编译器错误、协议一致性修复和可能的解决方法。
references/diagnostics.md - - 使用Swift Testing的异步测试策略、竞态检测、避免基于计时的测试。
references/testing.md