CodeToLive

Concurrency in Swift

Swift provides modern concurrency features including async/await, actors, and structured concurrency.

Async/Await

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

Task

Task {
    do {
        let data = try await fetchData()
        print("Data received")
    } catch {
        print("Error: \(error)")
    }
}

Actors

actor BankAccount {
    private var balance: Double = 0
    
    func deposit(amount: Double) {
        balance += amount
    }
    
    func withdraw(amount: Double) -> Double {
        balance -= amount
        return balance
    }
}

Async Sequences

for await line in URL(fileURLWithPath: "/path").lines {
    print(line)
}

Task Groups

func fetchMultiple() async throws -> [Data] {
    try await withThrowingTaskGroup(of: Data.self) { group in
        for url in urls {
            group.addTask { try await fetchData(from: url) }
        }
        
        var results = [Data]()
        for try await data in group {
            results.append(data)
        }
        return results
    }
}

Concurrency Comparison

Feature Description
async/await Write asynchronous code sequentially
Actors Reference types with synchronized access
Task Unit of asynchronous work
← Back to Tutorials