Token导航 LogoToken导航

Agent Skill · 研究检索

swift-concurrency(Swift 并发)

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

swift-concurrency 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 5,557。

总安装 25,401周安装 780GitHub Stars 142下载 7,230核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill 'Swift Concurrency'

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

swift-concurrency 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中快速定位候选结果。适用于需要根据关键词或任务场景进行信息筛选的场景,如 Swift 并发编程参考。通过关键词输入和来源线索,Agent 可生成结构化候选列表供进一步核验。

安装命令为 npx skills add https://github.com/thebushidocollective/han --skill 'Swift Concurrency'。使用前需确认权限范围和维护状态,注意是否触发联网或文件操作。

来源仓库内路径:skills/swift-concurrency

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/thebushidocollective/han --skill 'Swift Concur…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

swift-concurrency 怎么安装?

在终端执行 npx skills add https://github.com/thebushidocollective/han --skill 'Swift Concurrency'。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

swift-concurrency 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

swift-concurrency 需要什么权限?

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

swift-concurrency 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

swift-concurrency 用的人多吗?

公开数据是累计安装 25,401 次,近一周安装 780 次,下载 7,230 次,GitHub 142 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

swift-concurrency 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
swift-concurrency

Swift 并发 · 本页

25,401142需要联网MIT通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Swift Concurrency

Introduction

Swift's modern concurrency model provides structured, safe concurrent programming through async/await syntax, actors for data isolation, and task management primitives. This system eliminates common concurrency bugs like data races and callback hell while improving code readability and maintainability.

Introduced in Swift 5.5, the concurrency model integrates with the language's type system to enforce safety at compile time. Actors protect mutable state, async/await makes asynchronous code look synchronous, and structured concurrency ensures tasks are properly managed and cancelled.

This skill covers async functions, actors, task groups, cancellation, async sequences, and patterns for migrating from completion handlers to modern concurrency.

Async/Await Fundamentals

Async/await syntax enables writing asynchronous code that reads like synchronous code, without nested callbacks or complex error handling chains.

// Basic async function
func fetchUser(id: Int) async throws -> User {
    let url = URL(string: "https://api.example.com/users/\(id)")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(User.self, from: data)
}

// Calling async functions
func loadUserProfile() async {
    do {
        let user = try await fetchUser(id: 42)
        print("Loaded user: \(user.name)")
    } catch {
        print("Failed to load user: \(error)")
    }
}

// Sequential async calls
func loadFullProfile() async throws -> Profile {
    let user = try await fetchUser(id: 42)
    let posts = try await fetchPosts(userId: user.id)
    let comments = try await fetchComments(userId: user.id)

    return Profile(user: user, posts: posts, comments: comments)
}

// Parallel async calls with async let
func loadProfileParallel() async throws -> Profile {
    async let user = fetchUser(id: 42)
    async let posts = fetchPosts(userId: 42)
    async let comments = fetchComments(userId: 42)

    return try await Profile(
        user: user,
        posts: posts,
        comments: comments
    )
}

// Async properties
struct UserRepository {
    var currentUser: User {
        get async throws {
            return try await fetchUser(id: getCurrentUserId())
        }
    }
}

// Using async properties
func displayUser(repo: UserRepository) async {
    do {
        let user = try await repo.currentUser
        print(user.name)
    } catch {
        print("Error: \(error)")
    }
}

// Async initializers
class DataManager {
    let data: Data

    init() async throws {
        let url = URL(string: "https://api.example.com/config")!
        let (data, _) = try await URLSession.shared.data(from: url)
        self.data = data
    }
}

Async functions suspend execution at await points, allowing other work to proceed without blocking threads. The runtime manages suspension and resumption efficiently.

Actors for Safe Concurrency

Actors protect mutable state from concurrent access, preventing data races by ensuring only one task can access actor-isolated state at a time.

// Basic actor
actor Counter {
    private var value = 0

    func increment() {
        value += 1
    }

    func getValue() -> Int {
        return value
    }
}

// Using actors
func useCounter() async {
    let counter = Counter()

    await counter.increment()
    let value = await counter.getValue()
    print("Counter: \(value)")
}

// Actor with async methods
actor ImageCache {
    private var cache: [URL: Image] = [:]

    func image(for url: URL) async throws -> Image {
        if let cached = cache[url] {
            return cached
        }

        let (data, _) = try await URLSession.shared.data(from: url)
        guard let image = Image(data: data) else {
            throw ImageError.invalidData
        }

        cache[url] = image
        return image
    }

    func clear() {
        cache.removeAll()
    }
}

enum ImageError: Error {
    case invalidData
}

struct Image {
    init?(data: Data) {
        // Initialize image
        return nil
    }
}

// MainActor for UI updates
@MainActor
class ViewModel: ObservableObject {
    @Published var users: [User] = []

    func loadUsers() async {
        do {
            let fetchedUsers = try await fetchAllUsers()
            users = fetchedUsers // Safe: on main actor
        } catch {
            print("Failed to load users: \(error)")
        }
    }
}

func fetchAllUsers() async throws -> [User] {
    return []
}

// Nonisolated methods
actor DatabaseManager {
    private var connection: Connection?

    nonisolated func formatQuery(_ query: String) -> String {
        // Doesn't access actor state, no await needed
        return query.trimmingCharacters(in: .whitespaces)
    }

    func execute(_ query: String) async throws {
        // Accesses actor state
        guard let connection = connection else {
            throw DatabaseError.notConnected
        }
        // Execute query
    }
}

struct Connection {}
enum DatabaseError: Error {
    case notConnected
}

// Global actor for custom isolation
@globalActor
actor DatabaseActor {
    static let shared = DatabaseActor()
}

@DatabaseActor
class QueryBuilder {
    var table: String = ""

    func buildQuery() -> String {
        return "SELECT * FROM \(table)"
    }
}

Actors automatically serialize access to their state, eliminating data races while maintaining code clarity and avoiding manual lock management.

Structured Concurrency with Task Groups

Task groups enable spawning multiple concurrent tasks with automatic lifecycle management and result collection.

// Basic task group
func fetchMultipleUsers(ids: [Int]) async throws -> [User] {
    try await withThrowingTaskGroup(of: User.self) { group in
        for id in ids {
            group.addTask {
                try await fetchUser(id: id)
            }
        }

        var users: [User] = []
        for try await user in group {
            users.append(user)
        }
        return users
    }
}

// Non-throwing task group
func loadImages(urls: [URL]) async -> [Image] {
    await withTaskGroup(of: Image?.self) { group in
        for url in urls {
            group.addTask {
                try? await downloadImage(from: url)
            }
        }

        var images: [Image] = []
        for await image in group {
            if let image = image {
                images.append(image)
            }
        }
        return images
    }
}

func downloadImage(from url: URL) async throws -> Image {
    let (data, _) = try await URLSession.shared.data(from: url)
    guard let image = Image(data: data) else {
        throw ImageError.invalidData
    }
    return image
}

// Limited concurrency with task groups
func processItems<T>(
    _ items: [T],
    maxConcurrent: Int,
    process: @escaping (T) async throws -> Void
) async throws {
    try await withThrowingTaskGroup(of: Void.self) { group in
        var index = 0

        // Start initial batch
        for _ in 0..<min(maxConcurrent, items.count) {
            let item = items[index]
            group.addTask {
                try await process(item)
            }
            index += 1
        }

        // Process remaining items
        while index < items.count {
            try await group.next()
            let item = items[index]
            group.addTask {
                try await process(item)
            }
            index += 1
        }

        // Wait for remaining tasks
        try await group.waitForAll()
    }
}

// Task group with results dictionary
func fetchUserData(userIds: [Int]) async throws -> [Int: UserData] {
    try await withThrowingTaskGroup(
        of: (Int, UserData).self
    ) { group in
        for id in userIds {
            group.addTask {
                let data = try await loadUserData(id: id)
                return (id, data)
            }
        }

        var results: [Int: UserData] = [:]
        for try await (id, data) in group {
            results[id] = data
        }
        return results
    }
}

struct UserData {}

func loadUserData(id: Int) async throws -> UserData {
    return UserData()
}

// Early termination
func findFirstMatch(items: [String]) async -> String? {
    await withTaskGroup(of: String?.self) { group in
        for item in items {
            group.addTask {
                await checkMatch(item)
            }
        }

        for await result in group {
            if let match = result {
                group.cancelAll()
                return match
            }
        }
        return nil
    }
}

func checkMatch(_ item: String) async -> String? {
    // Simulate async work
    return item.count > 5 ? item : nil
}

Task groups provide structured concurrency: all child tasks complete or are cancelled before the group exits, preventing task leaks.

Task Management and Cancellation

Tasks represent units of asynchronous work with lifecycle management, cancellation support, and priority configuration.

// Creating detached tasks
func backgroundUpdate() {
    Task.detached(priority: .background) {
        await performHeavyComputation()
    }
}

func performHeavyComputation() async {
    // Heavy work
}

// Storing and cancelling tasks
class DataLoader {
    private var loadTask: Task<Data, Error>?

    func startLoading() {
        loadTask = Task {
            try await loadData()
        }
    }

    func cancelLoading() {
        loadTask?.cancel()
        loadTask = nil
    }

    func loadData() async throws -> Data {
        let url = URL(string: "https://api.example.com/data")!
        let (data, _) = try await URLSession.shared.data(from: url)
        return data
    }
}

// Checking for cancellation
func processLargeDataset(items: [Item]) async throws {
    for item in items {
        try Task.checkCancellation()
        await process(item)
    }
}

struct Item {}

func process(_ item: Item) async {
    // Process item
}

// Cooperative cancellation
func downloadWithProgress(url: URL) async throws -> Data {
    let (bytes, response) = try await URLSession.shared.bytes(from: url)

    var data = Data()
    for try await byte in bytes {
        if Task.isCancelled {
            throw CancellationError()
        }
        data.append(byte)
    }

    return data
}

// Task priorities
enum TaskPriority {
    case high, medium, low

    var priority: TaskPriority {
        switch self {
        case .high: return .high
        case .medium: return .medium
        case .low: return .low
        }
    }
}

func scheduleTask(priority: TaskPriority, work: @escaping () async -> Void) {
    Task(priority: priority.priority) {
        await work()
    }
}

// Task values and results
func loadUserAsync() async throws -> User {
    let task = Task<User, Error> {
        try await fetchUser(id: 1)
    }

    return try await task.value
}

// Unstructured tasks with context
@MainActor
class ViewController {
    func loadData() {
        Task { @MainActor in
            let data = try await fetchData()
            updateUI(with: data)
        }
    }

    func fetchData() async throws -> Data {
        return Data()
    }

    func updateUI(with data: Data) {
        // Update UI
    }
}

Tasks automatically inherit priority, task-local values, and actor context from their creation site, ensuring proper execution environment.

Async Sequences

Async sequences provide asynchronous iteration over values that arrive over time, enabling clean handling of streams, events, and paginated data.

// Basic async sequence
struct AsyncCountdown: AsyncSequence {
    typealias Element = Int

    let start: Int

    struct AsyncIterator: AsyncIteratorProtocol {
        var current: Int

        mutating func next() async -> Int? {
            guard current >= 0 else { return nil }
            let value = current
            current -= 1
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            return value
        }
    }

    func makeAsyncIterator() -> AsyncIterator {
        return AsyncIterator(current: start)
    }
}

// Using async sequences
func countDown() async {
    let countdown = AsyncCountdown(start: 5)
    for await number in countdown {
        print(number)
    }
}

// Async sequence operations
func processStream(urls: [URL]) async throws {
    let (bytes, _) = try await URLSession.shared.bytes(
        from: urls[0]
    )

    for try await byte in bytes {
        processByte(byte)
    }
}

func processByte(_ byte: UInt8) {
    // Process byte
}

// AsyncStream for custom sequences
func temperatures() -> AsyncStream<Double> {
    AsyncStream { continuation in
        let sensor = TemperatureSensor()
        sensor.onReading = { temperature in
            continuation.yield(temperature)
        }

        continuation.onTermination = { _ in
            sensor.stop()
        }

        sensor.start()
    }
}

class TemperatureSensor {
    var onReading: ((Double) -> Void)?

    func start() {}
    func stop() {}
}

// Using AsyncStream
func monitorTemperature() async {
    for await temp in temperatures() {
        print("Temperature: \(temp)°C")
        if temp > 100 {
            break
        }
    }
}

// Transforming async sequences
func filteredTemperatures() async {
    let temps = temperatures()
    for await temp in temps where temp > 0 {
        print("Positive temperature: \(temp)")
    }
}

// AsyncThrowingStream for errors
func networkEvents() -> AsyncThrowingStream<NetworkEvent, Error> {
    AsyncThrowingStream { continuation in
        let monitor = NetworkMonitor()

        monitor.onEvent = { event in
            continuation.yield(event)
        }

        monitor.onError = { error in
            continuation.finish(throwing: error)
        }

        monitor.start()
    }
}

struct NetworkEvent {}

class NetworkMonitor {
    var onEvent: ((NetworkEvent) -> Void)?
    var onError: ((Error) -> Void)?

    func start() {}
}

Async sequences integrate with for-await-in loops and support transformation, filtering, and composition like synchronous sequences.

Best Practices

  1. Use async/await instead of completion handlers to improve readability and avoid callback pyramids in new code
  2. Protect mutable state with actors rather than manual locks to prevent data races with compile-time guarantees
  3. Prefer structured concurrency with task groups over detached tasks to ensure proper lifecycle management and cancellation
  4. Check Task.isCancelled in long-running operations to enable cooperative cancellation and resource cleanup
  5. Use MainActor for UI code to ensure UI updates happen on the main thread without explicit dispatch calls
  6. Leverage async let for parallel execution when multiple independent async operations can run concurrently
  7. Employ async sequences for streams instead of callbacks or delegates when handling values that arrive over time
  8. Mark nonisolated methods appropriately on actors when they don't access isolated state to avoid unnecessary awaits
  9. Set task priorities explicitly for background work to prevent priority inversion and ensure responsive UI
  10. Use withTaskCancellationHandler to clean up resources immediately when tasks are cancelled rather than waiting for checkpoints

Common Pitfalls

  1. Blocking main thread with await in synchronous contexts causes hangs; create Task wrappers to bridge to async code
  2. Not checking for cancellation in long operations wastes resources and delays response to user actions
  3. Creating retain cycles with unowned/weak incorrectly in async closures can cause crashes or memory leaks
  4. Mixing async/await with completion handlers improperly creates race conditions and difficult-to-debug behavior
  5. Overusing detached tasks loses structured concurrency benefits like automatic cancellation and priority inheritance
  6. Forgetting await on actor methods causes compilation errors since actor isolation requires suspension points
  7. Not using throwing variants of task APIs when errors are possible leads to silent failures and unhandled errors
  8. Accessing actor state without isolation by making properties public defeats the purpose of actor protection
  9. Creating too many concurrent tasks without limits exhausts system resources and degrades performance
  10. Assuming immediate execution after await; other tasks may run before continuation, breaking assumptions about state

When to Use This Skill

Use Swift concurrency when building iOS 15+, macOS 12+, watchOS 8+, or tvOS 15+ applications that perform asynchronous operations like networking, file I/O, or background processing.

Apply async/await when working with URLSession, Core Data async methods, or any API that supports modern concurrency instead of completion handlers.

Employ actors when managing shared mutable state accessed from multiple concurrent contexts, especially in data managers, caches, or repositories.

Leverage task groups when performing multiple independent async operations that should be coordinated, like fetching data for multiple users or processing a batch of items concurrently.

Use async sequences when handling streams of data from sensors, network connections, file reading, or any source that produces values over time.

Resources

平台分布

Claude Code

27.42%
按下载量换算1,982

OpenCode

24.67%
按下载量换算1,784

Codex

18.87%
按下载量换算1,364

Antigravity

13.35%
按下载量换算965

windsurf

9.31%
按下载量换算673

Gemini CLI

4.09%
按下载量换算296

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

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

继续浏览同类 Skills