Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

swift-concurrency

БесплатноБез исполняемых скриптовНе проверен

Expert guidance on Swift Concurrency concepts. Use when working with async/await, Tasks, actors, MainActor, Sendable, isolation domains, or debugging…

tuistот tuist★ 159 звёзд на GitHub18 установок в других каталогах

Об этом скилле

Swift Concurrency Skill

This skill provides expert guidance on Swift's concurrency system based on the mental models from Fucking Approachable Swift Concurrency.

Core Mental Model: The Office Building

Think of your app as an office building where isolation domains are private offices with locks:

  • MainActor = Front desk (handles all UI interactions, only one exists)
  • actor types = Department offices (Accounting, Legal, HR - each protects its own data)
  • nonisolated code = Hallways (shared space, no private documents)
  • Sendable types = Photocopies (safe to share between offices)
  • Non-Sendable types = Original documents (must stay in one office)

You can't barge into someone's office. You knock (await) and wait.

Async/Await

An async function can pause. Use await to suspend until work finishes:

func fetchUser(id: Int) async throws -> User {
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(User.self, from: data)
}

For parallel work, use async let:

async let avatar = fetchImage("avatar.jpg")
async let banner = fetchImage("banner.jpg")
return Profile(avatar: try await avatar, banner: try await banner)

Tasks

A Task is a unit of async work you can manage:

// SwiftUI - cancels when view disappears
.task { avatar = await downloadAvatar() }

// Manual task creation
Task { await saveProfile() }

// Parallel work with TaskGroup
try await withThrowingTaskGroup(of: Void.self) { group in
    group.addTask { avatar = try await downloadAvatar() }
    group.addTask { bio = try await fetchBio() }
    try await group.waitForAll()
}

Child tasks in a group: cancellation propagates, errors cancel siblings, waits for all to complete.

Isolation Domains

Swift asks "who can access this data?" not "which thread?". Three isolation domains:

1. MainActor

For UI. Everything UI-related should be here:

@MainActor
class ViewModel {
    var items: [Item] = []  // Protected by MainActor
}

2. Actors

Protect their own mutable state with exclusive access:

actor BankAccount {
    var balance: Double = 0
    func deposit(_ amount: Double) { balance += amount }
}

await account.deposit(100)  // Must await from outside

3. Nonisolated

Opts out of actor isolation. Cannot access actor's protected state:

actor BankAccount {
    nonisolated func bankName() -> String { "Acme Bank" }
}
let name = account.bankName()  // No await needed

Approachable Concurrency (Swift 6.2+)

Two build settings that simplify the mental model:

  • SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor: Everything runs on MainActor unless you say otherwise
  • SWIFT_APPROACHABLE_CONCURRENCY = YES: nonisolated async functions stay on caller's actor
// Runs on MainActor (default)
func updateUI() async { }

// Runs on background (opt-in)
@concurrent func processLargeFile() async { }

Sendable

Marks types safe to pass across isolation boundaries:

// Sendable - value type, each gets a copy
struct User: Sendable {
    let id: Int
    let name: String
}

// Non-Sendable - mutable class state
class Counter {
    var count = 0
}

Automatically Sendable:

  • Structs/enums with only Sendable properties
  • Actors (protect their own state)
  • @MainActor types (MainActor serializes access)

For thread-safe classes with internal synchronization:

final class ThreadSafeCache: @unchecked Sendable {
    private let lock = NSLock()
    private var storage: [String: Data] = [:]
}

Isolation Inheritance

With Approachable Concurrency, isolation flows from MainActor through your code:

  • Functions: Inherit caller's isolation unless explicitly marked
  • Closures: Inherit from context where defined
  • Task { }: Inherits actor isolation from creation site
  • Task.detached { }: No inheritance (rarely needed)

Preserving Isolation in Async Utilities

When writing generic async functions that accept closures, you need to preserve the caller's isolation to avoid Sendable errors.

Option 1: nonisolated(nonsending) (simpler)

// Stays on caller's executor, no Sendable needed
nonisolated(nonsending)
func measure<T>(_ label: String, block: () async throws -> T) async rethrows -> T

Option 2: #isolation parameter (when you need actor access)

// Explicit isolation parameter, useful if you need to pass it around
func measure<T>(
    isolation: isolated (any Actor)? = #isolation,
    _ label: String,
    block: () async throws -> T
) async rethrows -> T

Use nonisolated(nonsending) by default. Use #isolation when you need explicit access to the actor instance.

Common Mistakes to Avoid

1. Thinking async = background

// Still blocks main thread!
@MainActor func slowFunction() async {
    let result = expensiveCalculation()  // Synchronous
Полный SKILL.md на GitHub

Установить swift-concurrency в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_layouts/base.njk_redirectsar/index.mdcss/style.cssen/index.mdes/index.mdfr/index.mdimages/apple-touch-icon.pngimages/favicon-16x16.pngimages/favicon-32x32.pngimages/favicon.svgimages/og-image.pngimages/og-image.svgja/index.mdko/index.mdpl/index.mdpt-BR/index.mdpt-PT/index.mdru/index.mdtr/index.mduk/index.mdzh-CN/index.mdzh-TW/index.md

FAQ

Что делает скилл swift-concurrency?

Expert guidance on Swift Concurrency concepts. Use when working with async/await, Tasks, actors, MainActor, Sendable, isolation domains, or debugging concurrency compiler errors. Helps write safe concurrent Swift code.

Как установить скилл swift-concurrency?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл swift-concurrency запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить swift-concurrency с