Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 46 ยท Concurrency and Performance

Concurrency in iOS: MainActor, Tasks and Async Work

Keep your iOS app responsive: the main thread rule, @MainActor, Task and the .task modifier, structured concurrency, Sendable and Swift 6 strict concurrency.

An iPhone screen redraws up to 60 or 120 times a second. To keep up, your app has a few milliseconds per frame to handle touches, update state and build views. If one of those steps stops to wait for the network or crunch a big file, the screen freezes: scrolling stutters, buttons feel dead, and in the worst case the system kills the app. Concurrency is how you keep slow work out of the way of the interface.

You already know the language side from the Swift track: async/await, tasks, actors and Sendable. This lesson applies them to an iOS app. You will learn the main thread rule, what @MainActor really means, how SwiftUI's .task modifier ties work to a view's lifetime, and what Swift 6 strict concurrency checks. SwiftUI itself cannot run on this site, so the view code is read-only. The runnable examples are plain Swift programs that use the real concurrency features.

The main thread rule

Every iOS app has a main thread that handles user input and draws the interface. UIKit and SwiftUI require that interface work happens there. Two rules follow:

  1. Do not block the main thread. No long loops, no synchronous file or network calls, no Thread.sleep. While it is busy, nothing on screen responds.
  2. Do not touch the UI from other threads. Changing what the screen shows from a background thread causes glitches or crashes.

Swift turns this convention into something the compiler understands: the main actor. An actor is an isolated region that runs one piece of code at a time. The main actor is the one tied to the main thread. Code marked @MainActor may touch UI state, and the compiler stops other code from touching it without await.

Who runs where?

Main actor Views, UI state, user input.
Background Parsing, image work, heavy loops.
Your actors One owner for shared data.

await marks every hop between them.

1 / 2

@MainActor in practice

You can put @MainActor on a function, a method, a property or a whole type. In a SwiftUI app you meet it in three places.

  • Views. In current SDKs a view's body is main-actor isolated, so view code is already on the main actor.
  • View models. Anything that holds state your views display should be @MainActor, so changing that state is safe. See MVVM in SwiftUI.
  • Project defaults. Recent versions of Xcode can set the default isolation of a whole app target to the main actor. Check your project's build settings to see which mode you have. If it is on, plain code in the app already counts as main-actor code, and you opt out for heavy work.

An async function does not leave the main actor just because it is async. A main-actor method that awaits something suspends and lets the main thread do other things, but its own code still resumes on the main actor. To make heavy work run elsewhere, put it in a function that is not isolated to the main actor. In Swift 6.2 and later, the attribute @concurrent says exactly that: "run this async function on the background pool."

The program below makes this visible. A small helper reports which actor the code is running on, using the #isolation macro. It is a real Swift 6 program. The view model is a stand-in for a class you would use with SwiftUI.

Swift Which actor am I on?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the output from top to bottom. load() starts on the main actor, sets the state to loading, and then hands the sum to a function that runs off the main actor. When the await finishes, load() resumes back on the main actor, so it is safe to write state. A plain Task { } inherits the main actor from the code that created it, while Task.detached starts with no actor. That is why a button action that creates a Task { } can update UI state directly.

The pattern to remember: state changes on the main actor, slow work in the background, results come back with await. Most of the time you do not need to write DispatchQueue.main.async or switch threads yourself.

Tasks in SwiftUI: the .task modifier

Starting async work from a view is so common that SwiftUI has a modifier for it. .task { } starts an async task when the view appears and cancels it when the view disappears. That second half matters: a user who leaves a screen should not leave a download running that will update a view nobody sees.

Swift
struct ProfileView: View {
    let userID: Int
    @State private var model = ProfileModel()

    var body: some View {
        Group {
            switch model.state {
            case .loading: ProgressView()
            case .loaded(let profile): Text(profile.name)
            case .failed(let message): Text(message)
            }
        }
        .task(id: userID) {
            await model.load(userID: userID)
        }
    }
}

This is read-only SwiftUI. .task(id: userID) adds a rule: when the value of userID changes, SwiftUI cancels the running task and starts a new one with the new value. That removes a whole class of "old response arrives after the new one" bugs.

The Task { } initializer is for work that starts from an event instead, such as a button tap. That task is not tied to the view, so you decide when to cancel it.

Swift
Button("Refresh") {
    Task { await model.refresh() }
}

A stand-in for .task(id:)

The stand-in below is a tiny class that reproduces the lifecycle: start on appear, cancel and restart when the id changes, cancel on disappear. The "work" is a pretend profile load that would take five seconds, and it reacts to cancellation the way real async code does.

Swift Task lifetime: appear, id change, disappear

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Profile 1 is cancelled when the id becomes 2, and profile 2 is cancelled when the view disappears. Neither waits five seconds, because Task.sleep throws CancellationError as soon as its task is cancelled. Your own long loops must check Task.isCancelled or call try Task.checkCancellation() to behave the same way. This is the cooperative cancellation you met in Cancellation and Timeouts.

Structured concurrency for parallel work

When several pieces of work are independent, start them together and wait for all. async let does it for a fixed number of jobs, and a task group does it for a list. Both are structured: the child tasks cannot outlive the scope that created them, and cancelling the parent cancels the children.

Swift async let and a task group with an actor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

On a screen, this is how you would load a profile and its badges for a header without waiting twice. The actor is the answer to "who owns this shared variable?": only one caller at a time runs inside it, so there is no data race. The details of both tools are in task groups and actors.

Sendable and Swift 6 strict concurrency

A data race happens when two threads use the same data at the same time and at least one of them changes it. The result is unpredictable: a wrong number, a corrupted array, a crash that appears once in a thousand runs. Swift 6 can prove most such races impossible at compile time. That is what strict concurrency checking does, and it is the default in the Swift 6 language mode. In an older project you can turn it on step by step with a build setting for strict concurrency checking (minimal, targeted, complete) before you switch the language mode.

The key idea is Sendable. A type is Sendable if it is safe to hand from one concurrency domain to another. Value types made of Sendable parts (structs, enums), actors and immutable classes qualify. A plain class with mutable properties does not. The compiler refuses to send it across a boundary.

Swift A data race the compiler refuses (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: non-Sendable type 'Counter' of let 'counter' cannot exit main actor-isolated context and a second error that the main actor-isolated counter cannot be accessed from outside the actor. Without that check, the detached task and the main actor could both change value at once. You have three honest fixes: make the data a Sendable value type and pass copies (like Profile above), keep the mutable state inside an actor (like ScoreBoard), or confine it to the main actor with @MainActor and do the work there.

Avoid silencing the compiler with @unchecked Sendable or nonisolated(unsafe) unless you can explain what protects the data (for example a lock). These tell the compiler "trust me", and a wrong promise brings the data race back.

Common mistakes

  • Blocking with a semaphore or Thread.sleep inside async code. It ties up a thread the runtime needs. Use await and Task.sleep.
  • Updating UI state from Task.detached. Hop back with await to a main-actor method, or return a value and let the main-actor code apply it.
  • Starting a Task in onAppear and forgetting to cancel it. Prefer .task, which cancels for you.
  • Making everything async "just in case". Cheap, synchronous work should stay synchronous. Add async where you actually wait.
  • Ignoring errors from a Task. An error thrown inside Task { } vanishes unless you catch it. Handle it and put a failed state in your model.
  • Forgetting that state can change between awaits. After an await, the world may have moved on, so re-check what you assumed before the suspension.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @MainActor on a class guarantee?

    @MainActor isolates the type to the main actor, which is tied to the main thread. It is about safety and isolation, not speed.
  2. 2. A button action contains Task { await model.refresh() }. On which actor does the new task run?

    A plain Task inherits the isolation, priority and task-local values of its creator. Task.detached is the one that starts with no actor.
  3. 3. What does .task(id: userID) do when userID changes?

    task(id:) restarts the work when the id changes, and the old task is cancelled, so stale results do not overwrite fresh ones.
  4. 4. Why does the compiler reject a detached task that mutates a plain mutable class instance?

    A non-Sendable mutable class is unsafe to share across domains. Swift 6 turns the possible data race into a compile error.
  5. 5. Which is a correct way to share a mutable counter between many tasks?

    An actor allows only one caller at a time inside it, so the counter has a single owner and no data race.

Summary

  • The main thread draws the UI; never block it, and never change UI state from other threads. Swift expresses this as the main actor.
  • Mark UI-facing types @MainActor; async code resumes on the actor it started on, and @concurrent (Swift 6.2+) sends heavy async work to the background.
  • A plain Task { } inherits the actor and priority of its creator; Task.detached inherits nothing.
  • .task { } starts on appear and cancels on disappear; .task(id:) restarts when the id changes. Cancellation is cooperative.
  • async let and task groups run independent work in parallel, and the children never outlive their scope.
  • Swift 6 strict concurrency uses Sendable and actors to turn data races into compile errors; prefer value types, actors and the main actor over @unchecked escape hatches.

Next: Performance, Instruments and Smooth Scrolling