Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计通过

swift-concurrencySwift 并发

Agent Skill

swift-concurrency 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

2,002

周安装

81

GitHub Stars

125

下载量

629
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:swift-concurrency(Swift 并发)
来源仓库:https://github.com/jamesrochabrun/skills
仓库路径:skills/swift-concurrency
安装命令:
npx skills add https://github.com/jamesrochabrun/skills --skill swift-concurrency
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/jamesrochabrun/skills --skill swift-concurrency

简介

swift-concurrency 用于查找、检索和筛选相关信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中根据关键词或任务场景快速定位候选结果。
  • 可结合来源仓库和原始 README 继续核验具体用法。
  • 安装命令:npx skills add https://github.com/jamesrochabrun/skills --skill swift-concurrency
  • 注意:安装前建议确认权限范围、维护状态及是否触发联网或文件操作。

SKILL.md

Swift Concurrency

Overview

This skill provides guidance for writing thread-safe Swift code using modern concurrency patterns. It covers three main workflows: building new async code, auditing existing code for issues, and refactoring legacy patterns to Swift 6+.

Core principle: Isolation is inherited by default. With Approachable Concurrency, code starts on MainActor and propagates through the program automatically. Opt out explicitly when needed.

Workflow Decision Tree

What are you doing?
│
├─► BUILDING new async code
│   └─► See "Building Workflow" below
│
├─► AUDITING existing code
│   └─► See "Auditing Checklist" below
│
└─► REFACTORING legacy code
    └─► See "Refactoring Workflow" below

Building Workflow

When writing new async code, follow this decision process:

Step 1: Determine Isolation Needs

Does this type manage UI state or interact with UI?
│
├─► YES → Mark with @MainActor
│
└─► NO → Does it have mutable state shared across contexts?
         │
         ├─► YES → Consider: Can it live on MainActor anyway?
         │         │
         │         ├─► YES → Use @MainActor (simpler)
         │         │
         │         └─► NO → Use a custom actor (requires justification)
         │
         └─► NO → Leave non-isolated (default with Approachable Concurrency)

Step 2: Design Async Functions

// PREFER: Inherit caller's isolation (works everywhere)
func fetchData(isolation: isolated (any Actor)? = #isolation) async throws -> Data {
  // Runs on whatever actor the caller is on
}

// USE WHEN: CPU-intensive work that must run in background
@concurrent
func processLargeFile() async -> Result { }

// AVOID: Non-isolated async without explicit choice
func ambiguousAsync() async { } // Where does this run?

Step 3: Handle Parallel Work

// For known number of independent operations
async let avatar = fetchImage("avatar.jpg")
async let banner = fetchImage("banner.jpg")
let (a, b) = await (avatar, banner)

// For dynamic number of operations
try await withThrowingTaskGroup(of: Void.self) { group in
  for id in userIDs {
    group.addTask { try await fetchUser(id) }
  }
  try await group.waitForAll()
}

Step 4: SwiftUI Integration

struct ProfileView: View {
  @State private var avatar: Image?

  var body: some View {
    avatar
      .task { avatar = await downloadAvatar() }  // Auto-cancels on disappear
      .task(id: userID) { /* Reloads when userID changes */ }
  }
}

// For user actions
Button("Save") {
  Task { await saveProfile() }  // Inherits MainActor isolation
}

Auditing Checklist

When reviewing Swift concurrency code, check for these issues:

Critical Issues (Must Fix)

  • Blocking the cooperative pool: Look for DispatchSemaphore.wait(), DispatchGroup.wait(), or similar blocking calls inside async contexts
  • Data races: Non-Sendable types crossing isolation boundaries without proper handling
  • Non-isolated async in non-Sendable types: These only work from non-isolated contexts

Common Issues (Should Fix)

  • Actor overuse: Custom actors without justification (see "Actor Justification Test" in references)
  • Unnecessary MainActor.run: Should usually be @MainActor on the function instead
  • Thinking async = background: Synchronous CPU work inside async functions still blocks
  • Unstructured Tasks where structured works: Task {} instead of async let or TaskGroup
  • Missing cancellation handling: Long operations should check Task.isCancelled

SwiftUI-Specific

  • Views not MainActor-isolated: SwiftUI views should be @MainActor (or use @Observable)
  • Accessing @State from detached tasks: Must hop back to MainActor

Sendable Compliance

  • @unchecked Sendable overuse: Should be rare and justified
  • Making everything Sendable: Not all types need to cross boundaries
  • Non-Sendable closures escaping: Check closure captures

Refactoring Workflow

From Callbacks to async/await

// BEFORE: Callback-based
func fetchUser(id: Int, completion: @escaping (Result<User, Error>) -> Void) {
  URLSession.shared.dataTask(with: url) { data, _, error in
    if let error { completion(.failure(error)); return }
    // ...
  }.resume()
}

// AFTER: async/await with continuation
func fetchUser(id: Int) async throws -> User {
  try await withCheckedThrowingContinuation { continuation in
    fetchUser(id: id) { result in
      continuation.resume(with: result)
    }
  }
}

From DispatchQueue to Actors

// BEFORE: Queue-based protection
class BankAccount {
  private let queue = DispatchQueue(label: "account")
  private var _balance: Double = 0

  var balance: Double {
    queue.sync { _balance }
  }

  func deposit(_ amount: Double) {
    queue.async { self._balance += amount }
  }
}

// AFTER: Actor (if truly needs own isolation)
actor BankAccount {
  var balance: Double = 0

  func deposit(_ amount: Double) {
    balance += amount
  }
}

// BETTER: MainActor class (if doesn't need concurrent access)
@MainActor
class BankAccount {
  var balance: Double = 0

  func deposit(_ amount: Double) {
    balance += amount
  }
}

From Combine to AsyncSequence

// BEFORE: Combine publisher
cancellable = NotificationCenter.default
  .publisher(for: .userDidLogin)
  .sink { notification in /* ... */ }

// AFTER: AsyncSequence
for await _ in NotificationCenter.default.notifications(named: .userDidLogin) {
  // Handle notification
}

Quick Reference

KeywordPurpose
asyncFunction can suspend
awaitSuspension point
Task {}Start async work, inherits isolation
Task.detached {}Start async work, no inheritance
@MainActorRuns on main thread
actorType with isolated mutable state
nonisolatedOpts out of actor isolation
nonisolated(nonsending)Inherits caller's isolation
@concurrentAlways run on background (Swift 6.2+)
SendableSafe to cross isolation boundaries
sendingOne-way transfer of non-Sendable
async letStart parallel work
TaskGroupDynamic parallel work

Approachable Concurrency Settings (Swift 6.2+)

For new Xcode 26+ projects, these are enabled by default:

SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor
SWIFT_APPROACHABLE_CONCURRENCY = YES

Effects:

  • Everything runs on MainActor unless explicitly marked otherwise
  • nonisolated async functions stay on caller's actor instead of hopping to background
  • Sendable errors become much rarer

Resources

For detailed technical reference, consult:

  • references/fundamentals.md - async/await, Tasks, structured concurrency
  • references/isolation.md - Actors, MainActor, isolation domains, inheritance
  • references/sendable.md - Sendable protocol, non-Sendable patterns, isolated parameters
  • references/common-mistakes.md - Detailed examples of what to avoid
  • references/glossary.md - Complete terminology reference

Search patterns for references:

  • Isolation: grep -i "isolation\|actor\|mainactor\|nonisolated"
  • Sendable: grep -i "sendable\|sending\|boundary"
  • Tasks: grep -i "task\|taskgroup\|async let\|structured"

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

26.07%
按下载量换算164

OpenCode

22.71%
按下载量换算143

windsurf

17.56%
按下载量换算110

Gemini CLI

12.28%
按下载量换算77

Antigravity

7.42%
按下载量换算47

Codex

3.22%
按下载量换算20

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills