Claude
Skills
Sign in
Back

Swift Concurrency

Included with Lifetime
$97 forever

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.

Productivity

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 tr

Related in Productivity