Skip to content

Concurrency

Concurrency allows your application to perform multiple tasks at the same time. This keeps your program fast and responsive even while it handles heavy workloads in the background.

Async / Await

Modern Swift uses async and await keywords to handle asynchronous tasks. This allows you to write complex background code that reads cleanly from top to bottom, exactly like standard code.

swift
func fetchData() async -> String {
    // Simulate network delay
    try? await Task.sleep(nanoseconds: 1 * 1_000_000_000)
    return "Data received"
}

Task {
    let data = await fetchData()
    print(data)
}

Structured Concurrency (async let)

You can use async let to run multiple background tasks in parallel. This saves a massive amount of time by executing them simultaneously and then waiting for all of them to finish before moving forward.

swift
async let first = fetchData()
async let second = fetchData()

let results = await [first, second]

Actors

Actors are reference types that behave similarly to standard classes but are specifically designed to protect their state from data races. They ensure that only one single task can access or modify their properties at a time, completely preventing overlapping changes that cause mysterious crashes.

swift
actor BankAccount {
    var balance = 0
    
    func deposit(amount: Int) {
        balance += amount
    }
}

@MainActor

This is a specialized actor that guarantees your code runs strictly on the main thread. You must use this whenever you are updating the visual user interface to ensure the screen refreshes safely.

swift
@MainActor
func updateUI() {
    // Update labels, buttons, etc.
}