swift-concurrency-pro

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Review 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:
  1. Scan for known-dangerous patterns using
    references/hotspots.md
    to prioritize what to inspect.
  2. Check for recent Swift 6.2 concurrency behavior using
    references/new-features.md
    .
  3. Validate actor usage for reentrancy and isolation correctness using
    references/actors.md
    .
  4. Ensure structured concurrency is preferred over unstructured where appropriate using
    references/structured.md
    .
  5. Check unstructured task usage for correctness using
    references/unstructured.md
    .
  6. Verify cancellation is handled correctly using
    references/cancellation.md
    .
  7. Validate async stream and continuation usage using
    references/async-streams.md
    .
  8. Check bridging code between sync and async worlds using
    references/bridging.md
    .
  9. Review any legacy concurrency migrations using
    references/interop.md
    .
  10. Cross-check against common failure modes using
    references/bug-patterns.md
    .
  11. If the project has strict-concurrency errors, map diagnostics to fixes using
    references/diagnostics.md
    .
  12. If reviewing tests, check async test patterns using
    references/testing.md
    .
If doing a partial review, load only the relevant reference files.
审查Swift并发代码的正确性、现代API使用情况以及是否符合项目规范。仅报告真实存在的问题——不要吹毛求疵或捏造问题。
审查流程:
  1. 使用
    references/hotspots.md
    扫描已知危险模式,确定优先检查的内容。
  2. 参考
    references/new-features.md
    检查Swift 6.2的最新并发行为。
  3. 使用
    references/actors.md
    验证Actor的可重入性和隔离正确性。
  4. 根据实际情况,优先选择结构化并发而非非结构化并发,参考
    references/structured.md
  5. 使用
    references/unstructured.md
    检查非结构化任务的使用正确性。
  6. 使用
    references/cancellation.md
    验证取消操作是否处理正确。
  7. 使用
    references/async-streams.md
    验证异步流和continuation的使用。
  8. 使用
    references/bridging.md
    检查同步与异步代码之间的桥接逻辑。
  9. 参考
    references/interop.md
    审查任何遗留并发代码的迁移情况。
  10. 使用
    references/bug-patterns.md
    交叉检查常见故障模式。
  11. 如果项目存在严格并发错误,参考
    references/diagnostics.md
    将诊断信息映射到修复方案。
  12. 如果审查测试代码,参考
    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
    async
    /
    await
    and closure-based variants, always prefer
    async
    /
    await
    .
  • Do not introduce third-party concurrency frameworks without asking first.
  • Do not suggest
    @unchecked Sendable
    to fix compiler errors. It silences the diagnostic without fixing the underlying race. Prefer actors, value types, or
    sending
    parameters instead. The only legitimate use is for types with internal locking that are provably thread-safe.
  • 目标为Swift 6.2或更高版本,并启用严格并发检查。
  • 如果代码跨多个目标或包,在假设行为应一致之前,先比较它们的并发构建设置。
  • 优先使用结构化并发(任务组)而非非结构化并发(
    Task {}
    )。
  • 新代码优先使用Swift并发而非Grand Central Dispatch。在底层代码、框架互操作或性能关键的同步工作中,队列和锁是合适工具的情况下,GCD仍然可以接受——不要将这些标记为错误。
  • 如果某个API同时提供
    async
    /
    await
    和基于闭包的变体,始终优先选择
    async
    /
    await
  • 未经许可,不要引入第三方并发框架。
  • 不要建议使用
    @unchecked Sendable
    来修复编译器错误。这会掩盖诊断信息但不会修复潜在的竞态条件。优先选择Actor、值类型或
    sending
    参数。唯一合理的使用场景是具有内部锁且可证明线程安全的类型。

Output Format

输出格式

Organize findings by file. For each issue:
  1. State the file and relevant line(s).
  2. Name the rule being violated.
  3. 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:
按文件整理发现的问题。对于每个问题:
  1. 说明文件和相关行号。
  2. 指出违反的规则。
  3. 展示简短的修复前后代码对比。
跳过没有问题的文件。最后给出按优先级排序的最具影响的修改总结。
示例输出:

DataLoader.swift

DataLoader.swift

Line 18: Actor reentrancy – state may have changed across the
await
.
swift
// 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
withTaskGroup
instead of creating tasks in a loop.
swift
// 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可重入性——
await
期间状态可能已更改。
swift
// 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行:使用
withTaskGroup
替代在循环中创建任务。
swift
// 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

总结

  1. Correctness (high): Actor reentrancy bug on line 18 may cause duplicate downloads and a force-unwrap crash.
  2. Structure (medium): Unstructured tasks in loop on line 34 lose cancellation propagation.
End of example.
  1. 正确性(高优先级): 第18行的Actor可重入漏洞可能导致重复下载和强制解包崩溃。
  2. 结构(中优先级): 第34行循环中的非结构化任务会丢失取消传播。
示例结束。

References

参考资料

  • references/hotspots.md
    - Grep targets for code review: known-dangerous patterns and what to check for each.
  • references/new-features.md
    - Swift 6.2 changes that alter review advice: default actor isolation, isolated conformances, caller-actor async behavior,
    @concurrent
    ,
    Task.immediate
    , task naming, and priority escalation.
  • references/actors.md
    - Actor reentrancy, shared-state annotations, global actor inference, and isolation patterns.
  • references/structured.md
    - Task groups over loops, discarding task groups, concurrency limits.
  • references/unstructured.md
    - Task vs Task.detached, when Task {} is a code smell.
  • references/cancellation.md
    - Cancellation propagation, cooperative checking, broken cancellation patterns.
  • references/async-streams.md
    - AsyncStream factory, continuation lifecycle, back-pressure.
  • references/bridging.md
    - Checked continuations, wrapping legacy APIs,
    @unchecked Sendable
    .
  • references/interop.md
    - Migrating from GCD,
    Mutex
    /locks, completion handlers, delegates, and Combine.
  • references/bug-patterns.md
    - Common concurrency failure modes and their fixes.
  • references/diagnostics.md
    - Strict-concurrency compiler errors, protocol conformance fixes, and likely remedies.
  • references/testing.md
    - Async test strategy with Swift Testing, race detection, avoiding timing-based tests.
  • references/hotspots.md
    - 代码审查的 grep 目标:已知危险模式及每种模式的检查要点。
  • references/new-features.md
    - 改变审查建议的Swift 6.2变更:默认Actor隔离、隔离一致性、调用方Actor异步行为、
    @concurrent
    Task.immediate
    、任务命名和优先级提升。
  • references/actors.md
    - Actor可重入性、共享状态注解、全局Actor推断和隔离模式。
  • references/structured.md
    - 用任务组替代循环、丢弃任务组、并发限制。
  • references/unstructured.md
    - Task与Task.detached的区别,
    Task {}
    何时是代码异味。
  • references/cancellation.md
    - 取消传播、协作式检查、存在问题的取消模式。
  • references/async-streams.md
    - AsyncStream工厂、continuation生命周期、背压。
  • references/bridging.md
    - 受检continuation、包装遗留API、
    @unchecked Sendable
  • references/interop.md
    - 从GCD迁移、
    Mutex
    /锁、完成处理器、委托和Combine。
  • references/bug-patterns.md
    - 常见并发故障模式及其修复方案。
  • references/diagnostics.md
    - 严格并发编译器错误、协议一致性修复和可能的解决方法。
  • references/testing.md
    - 使用Swift Testing的异步测试策略、竞态检测、避免基于计时的测试。