Swift Concurrency
Use when swift's modern concurrency model including async/await, actors, task groups, structured concurrency, and async sequences for building safe, performant concurrent code without data races or callback pyramids.
What this skill does
# 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.
```swift
// 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.
```swift
// 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.
```swift
// 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 trRelated in Productivity
gitea-workflow
IncludedOrchestrate agile development workflows for Gitea repositories using the tea CLI. Use when working with Gitea-hosted repos and asking to 'run the workflow', 'continue working', 'what's next', 'complete the task cycle', 'start my day', 'end the sprint', 'implement the next task', or wanting guided step-by-step development assistance. Keywords: workflow, orchestrate, agile, task cycle, sprint, daily, implement, review, PR, standup, retrospective, gitea, tea.
microsoft-graph-gateway
IncludedRoute Microsoft Graph work in this workspace. Use when users want to read or write Outlook mail, calendar events, contacts, OneDrive or SharePoint files, Teams, Planner, To Do, users, groups, directory data, or arbitrary Microsoft Graph endpoints from VS Code. Prefer WorkIQ for common read scenarios. Use Microsoft Graph for write actions and gap-read scenarios that need exact Graph properties, filters, permissions, or endpoints.
copilotkit
IncludedUse when building with CopilotKit — setup, development, integrations, debugging, upgrading, or contributing. Routes to the appropriate specialized skill based on the task.
wordly-wisdom
IncludedProvides calibrated decision analysis using Charlie Munger-style multiple mental models, inversion, incentive mapping, circle-of-competence checks, misjudgment audits, second-order effects, and forecast updates. Use when the user asks for an oracle take, a hard call, a decision memo, a premortem, an outside view, a red-team, a sanity-check, what am I missing, think this through, or wants a strategy, hire, investment, plan, product, partnership, or major life choice analysed. Avoid for simple factual lookups or time-sensitive legal, medical, or market questions without fresh evidence.
swain-session
IncludedSession management and project status dashboard. Owns the full session lifecycle (start/work/close/resume), focus lane, bookmarks, worktree detection, and tab naming. Also serves as the project status dashboard — shows active epics, progress, actionable next steps, blocked items, tasks, GitHub issues, and recommendations. Worktree creation is deferred to swain-do task dispatch (SPEC-195). Triggers on: 'session', 'status', 'what's next', 'dashboard', 'overview', 'where are we', 'what should I work on', 'show me priorities', 'bookmark', 'focus on', 'session info'.
gandi
IncludedComprehensive Gandi domain registrar integration for domain and DNS management. Register and manage domains, create/update/delete DNS records (A, AAAA, CNAME, MX, TXT, SRV, and more), configure email forwarding and aliases, check SSL certificate status, create DNS snapshots for safe rollback, bulk update zone files, and monitor domain expiration. Supports multi-domain management, zone file import/export, and automated DNS backups. Includes both read-only and destructive operations with safety controls.