skip to content

Async and Isolation

async and await, structured tasks, async sequences, actors and Sendable checking: the model Swift 6 enforces at compile time. Interviewers ask about isolation and data races.

on this pageshow

explore

questions

page 1 of 2

In Swift, what does marking a view model class `@MainActor` guarantee, and how does background work hand its results back to it?

level: juniorimportance: must knowfreq 80%

answer

  1. an actor named by an attribute
  2. every member isolated to one actor
  3. await to hop onto it
  4. MainActor.run or a @MainActor closure

basics

~20 s

@MainActor isolates every property and method of the class to the main actor, so the compiler lets only main-actor code touch them synchronously. Background code reaches the view model with await: an isolated method, MainActor.run, or a @MainActor closure.

solid answer

~50 s

`@MainActor` names the main actor, a **global actor**: one shared actor identified by its type, so an attribute is enough to isolate a declaration to it, and code on the main actor runs on the main thread. On a class it isolates every stored property, method and declared initializer, including those in extensions, except members marked `nonisolated`. The guarantee is checked at compile time: a nonisolated function that assigns `model.titles` is rejected with "main actor-isolated property 'titles' can not be mutated from a nonisolated context". Background work therefore hops: `await model.apply(results)` calls an isolated method, `await MainActor.run { ... }` runs a closure there and returns a `Sendable` result, and `Task { @MainActor in ... }` schedules it without waiting. Inside an isolated `async` method, awaiting a nonisolated `async` function runs that work off the main actor and resumes on it afterwards, in Swift 5 and Swift 6 modes.

code

swift · 28 lines
swift
@MainActor
final class GalleryViewModel {
    var titles: [String] = []
    var isLoading = false

    func reload() async {
        isLoading = true                       // on the main actor
        let fresh = await fetchTitles()        // runs off the main actor
        titles = fresh                         // back on the main actor
        isLoading = false
    }
}

nonisolated func fetchTitles() async -> [String] {
    ["Beach", "Forest"]
}

func refreshFromBackground(_ model: GalleryViewModel) async {
    await model.reload()                       // hop to the main actor
    let count = await MainActor.run { model.titles.count }
    print(count)
}

func notifyLater(_ model: GalleryViewModel) {
    Task { @MainActor in
        model.isLoading = false
    }
}

go deeper

for a junior

Recall that @MainActor isolates a type's members to the main actor, and that code elsewhere reaches them with await or a @MainActor closure.

for a middle

Explain global actors, which members the attribute covers, and where an awaited nonisolated async function runs inside an isolated method.

for a senior

Pick the right hand-off for each case, explain why assumeIsolated traps instead of hopping, and spot reentrancy in overlapping reload calls.

for a principal

Decide how much of a module is main-actor isolated and how CPU-heavy work leaves it, so isolation stays simple without blocking the UI.

## The main actor is a global actor An ordinary actor can have many instances, each with its own isolated state, so code names the instance it calls. A **global actor** is a singleton: its type has a `static let shared` instance, and the type alone identifies the actor. That is why it can be written as an attribute. `MainActor` is the global actor the standard library provides, and the Swift book describes it as the actor that protects the data used to show an app's UI. When code runs on the main actor, Swift executes it on the main thread; the book calls the thread the lower-level detail and the actor what your code interacts with. You can declare your own global actor with `@globalActor` on an actor that provides `shared`, but most app code needs only the main actor. ## What `@MainActor` on a class isolates Writing `@MainActor final class GalleryViewModel` applies main-actor isolation to the whole type: - every stored property, so reads and writes happen only on the main actor; - every method, computed property and subscript, including those in extensions of the type; - the initializers you declare (in Swift 6 mode a synthesized no-argument initializer can stay nonisolated when every default value can be computed outside the actor); - subclasses of an isolated class, and conformers of a `@MainActor` protocol, which pick up the isolation; - but not members marked `nonisolated`, which opt out and so cannot touch isolated state; and not `deinit`, which is nonisolated unless declared `isolated deinit` (Swift 6.2). You can also isolate single members, `@MainActor func render()`, or a closure, `{ @MainActor in ... }`. The guarantee is **static**. From a nonisolated synchronous function, `model.titles = []` fails with "main actor-isolated property 'titles' can not be mutated from a nonisolated context", and from a nonisolated `async` function the same assignment fails too: `await` does not license setting an isolated property from outside. Calls to isolated methods from outside the main actor are asynchronous and written with `await`. ## Three ways to hand results back | Technique | Caller waits? | Returns a value? | Typical use | |---|---|---|---| | `await model.apply(results)` | yes | if the method returns one | the view model owns the update logic | | `await MainActor.run { ... }` | yes | yes, a `Sendable` result | a few lines that must run on the main actor | | `Task { @MainActor in ... }` | no | through the task handle | fire-and-forget from synchronous code | `MainActor.run` is declared as `static func run<T: Sendable>(resultType:body:) async rethrows -> T`, with a `@MainActor @Sendable` body. The result is `Sendable` because it crosses back to the caller's isolation domain. ## The `await` inside an isolated method The most common shape needs no explicit hop at all. Make the loading method part of the view model: 1. `reload()` is isolated to the main actor, so it sets `isLoading = true` directly. 2. It awaits `fetchTitles()`, a nonisolated `async` function. In Swift 5 and Swift 6 language modes such a function runs on the generic executor, off the main actor, so the main actor is free to handle other work while the fetch is in flight. 3. When the fetch returns, `reload()` resumes on the main actor and assigns `titles`. With the upcoming feature `NonisolatedNonsendingByDefault` (Swift 6.2, a future-mode feature that Swift 6 mode does not turn on), nonisolated async functions run on their caller's actor instead; that switch is covered with Sendable and data-race safety. Because `reload()` suspends at its `await`, another call to it can start in the meantime, the reentrancy hazard the lesson on actors and reentrancy explains. ## When the compiler cannot see the main actor Some synchronous callbacks are documented to arrive on the main thread but are declared nonisolated, so the compiler cannot prove it. `MainActor.assumeIsolated { ... }` (Swift 5.9) checks at run time that the current executor is the main actor's and then runs the closure as main-actor code synchronously; if the check fails, the program stops with a fatal error. It is marked unavailable from async code, where you write `await` instead. `MainActor.assertIsolated()` only checks, and does nothing in `-O` builds. ## Common mistakes - Expecting `@MainActor` to push a nonisolated `async` function's work onto the main thread. - Using `MainActor.assumeIsolated` as a hop: it never moves work, it verifies or traps. - Writing `await` before a property assignment from background code instead of calling a method. - Forgetting that how a UI framework creates and observes the view model is the framework's lesson; this one is about the language rule.

  • When would you use `MainActor.assumeIsolated` instead of `await`?
    In a synchronous callback that you know arrives on the main thread but that the compiler sees as nonisolated, such as a delegate method from an older API. `MainActor.assumeIsolated { ... }` checks that the current executor is the main actor's and runs the closure as main-actor code; if the check fails the program stops with a fatal error. It cannot be called from async code, where a plain `await` does the hop.
  • Why does `MainActor.run` require its result type to be `Sendable`?
    The closure runs on the main actor and its result is handed back to the caller, which may be isolated elsewhere. A non-Sendable result, such as a mutable class instance, would then be shared between two isolation domains. The declaration constrains `T: Sendable` so only values that are safe to cross come back; keep the main-actor objects on the main actor and return plain values.

  • @MainActor makes every awaited call inside a method run on the main thread.
  • Writing await before model.titles = value from background code is enough.
  • MainActor.assumeIsolated hops to the main actor like MainActor.run does.
  • @MainActor is checked only at run time, by asserting the current thread.
  • Methods added in an extension of a @MainActor class are nonisolated unless marked again.

Assumes Swift 6.4 in Swift 5 or Swift 6 language mode; with the upcoming feature NonisolatedNonsendingByDefault (Swift 6.2, not on in Swift 6 mode) a nonisolated async function runs on its caller's actor instead.

open as a page

In Swift, what does `await` mark inside an async function, and what happens to the thread when the function suspends there?

level: juniorimportance: must knowfreq 75%

basics

~20 s

await marks a possible suspension point. If the call does suspend, the async function gives up its thread instead of blocking it, other work runs there, and the function later resumes, perhaps on another thread, where shared state may have changed.

open as a page

With GCD, how do serial and concurrent DispatchQueues differ, and why must a star-chart screen's UI update go back to DispatchQueue.main?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A serial DispatchQueue runs one work item at a time, in order; a concurrent queue starts items in order but can run several at once. DispatchQueue.main is a serial queue tied to the main thread, where all UIKit and SwiftUI updates belong.

open as a page

In Swift, how does a for await loop over an AsyncSequence work, when does it need try, and what ends it?

level: juniorimportance: must knowfreq 55%

basics

~20 s

A for await loop awaits its iterator's next() before every pass, suspending until the next value or the end. It needs for try await when the sequence can throw, and ends when next() returns nil or throws, or the body breaks.

open as a page

In Swift, how does `Task { }` start async work from a synchronous button action, and what does the returned handle let you do?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Task { } creates an unstructured task that starts at once and returns a Task<Success, Failure> handle. Keep the handle to await value or result or to call cancel(); dropping it neither cancels the task nor surfaces its errors.

open as a page

In Swift, what changes when a shared thumbnail cache is declared as an `actor` rather than a class, and why must callers write `await`?

level: middleimportance: must knowfreq 72%

basics

~20 s

An actor is a reference type whose mutable state only its own code can touch, one task at a time. Outside code reaches that state through asynchronous calls, marked with await because the caller may have to wait.

open as a page

On a Swift forecast screen that needs a forecast and an air-quality reading, how do two sequential awaits differ from two `async let` bindings?

level: middleimportance: must knowfreq 65%

basics

~20 s

Sequential awaits run the requests in turn, so the wait is their sum. Each async let starts its call at once as a child task, awaited where the value is used, so the wait is roughly the slower request.

open as a page

How do you wrap a legacy Swift location SDK's `requestLocation(completion:)` callback in an `async throws` function using `withCheckedThrowingContinuation`?

level: middleimportance: must knowfreq 60%

basics

~10 s

Call the SDK inside withCheckedThrowingContinuation and, in its completion handler, resume the continuation exactly once: resume(returning:) with the location or resume(throwing:) with the error. Callers then simply try await the wrapper.

open as a page

With GCD's DispatchGroup, how do you download several star-chart tiles in parallel and draw the constellation only after every download has finished?

level: middleimportance: must knowfreq 58%

basics

~20 s

Call enter() on a DispatchGroup before each tile request, call leave() exactly once when that request completes, and register notify(queue: .main) to draw. The notify block runs once the count reaches zero, without blocking any thread.

open as a page

In Swift, when does a struct, enum or class conform to Sendable, and what must a final class satisfy to declare it?

level: middleimportance: must knowfreq 70%

basics

~20 s

A struct or enum is Sendable when every stored property or associated value is; non-public ones usually conform implicitly. A class passes the check only if it is final, stores only Sendable let properties and inherits from nothing but NSObject.

open as a page

How do you turn a chat socket's delegate callbacks into a Swift AsyncThrowingStream that a screen reads with for try await?

level: middleimportance: must knowfreq 60%

basics

~20 s

Create an AsyncThrowingStream, keep its Continuation where the delegate methods can reach it, call yield(_:) per message and finish(throwing:) when the socket closes, and close the socket in onTermination. makeStream(of:) returns stream and continuation together.

open as a page

In Swift, what does calling `cancel()` on a `Task` actually do, and how should the task's own code notice and respond?

level: middleimportance: must knowfreq 72%

basics

~20 s

Calling cancel() on a Swift Task only sets its cancelled flag, which also reaches its child tasks; nothing stops by force. The code must check Task.isCancelled or call Task.checkCancellation(), then stop by throwing CancellationError or returning partial results.

open as a page

In Swift, what does a `Task { }` created inside a `@MainActor` method inherit, and why is `Task.detached` rarely the right tool?

level: middleimportance: must knowfreq 70%

basics

~20 s

Task { } inherits the creator's actor isolation, base priority and task-local values, but not its cancellation. Task.detached inherits none of these, so it is rarely right: you lose context and must hop back to the main actor yourself.

open as a page

A Swift actor thumbnail cache checks its dictionary, awaits a download, then stores the image; why can two screens trigger the same download, and how do you fix it?

level: seniorimportance: must knowfreq 62%

basics

~20 s

Swift actors are reentrant: while one call waits at an await, other calls run on the actor, so both callers miss the cache before either download finishes. Store an in-flight Task before suspending and let later callers await it.

open as a page

With GCD, why does a star-map screen hang or crash when main-thread code calls DispatchQueue.main.sync, and how do you prevent it?

level: seniorimportance: must knowfreq 62%

basics

~20 s

DispatchQueue.main.sync blocks the caller until its block has run on the main thread, but the caller is the main thread, so the block can never start: a deadlock. Use DispatchQueue.main.async instead, and assert queue expectations with dispatchPrecondition.

open as a page

In Swift 6 language mode, why may a Task capture a freshly created non-Sendable ResponseCache but not one stored on self, and what does sending add?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Region-based isolation lets a non-Sendable value move into a Task when nothing else can reach it afterwards: a fresh local cache can, one reached through self cannot, because the caller still holds self. A sending parameter writes that hand-over into a signature.

open as a page

In Swift, what does marking an actor member `nonisolated` allow and forbid, and what does an `isolated` parameter do instead?

level: middleimportance: should knowfreq 40%

basics

~20 s

A nonisolated actor member runs outside the actor: any code may use it without await, but it reads only immutable Sendable state. An isolated parameter does the reverse: the function runs on the actor passed in.

open as a page

With GCD, how does a .barrier work item on a custom concurrent DispatchQueue protect a thumbnail cache that many queues read and one writes?

level: middleimportance: should knowfreq 42%

basics

~20 s

Reads run with queue.sync on a custom concurrent queue, so many proceed at once; writes use queue.async(flags: .barrier), which waits for earlier items, runs alone, then lets later items continue. The flag only works on a queue you created with .concurrent.

open as a page

With OperationQueue, how do addDependency(_:), maxConcurrentOperationCount and cancelAllOperations() control tile download operations and the drawing step that depends on them?

level: middleimportance: should knowfreq 35%

basics

~20 s

addDependency(_:) keeps the draw operation from becoming ready until every download it depends on has finished, even across queues; maxConcurrentOperationCount caps how many downloads one queue runs at once; cancelAllOperations() only marks operations cancelled, so running ones must check isCancelled.

open as a page

In Swift, what happens when two tasks iterate the same AsyncStream or AsyncThrowingStream of chat messages, and how do you give both every message?

level: middleimportance: should knowfreq 40%

basics

~10 s

Neither gets every message: streams are single-consumer, and concurrent iteration is documented as a programmer error. In Swift 6.4 AsyncStream splits elements between waiting tasks and AsyncThrowingStream traps. Give each subscriber its own stream.

open as a page

In Swift, how does a `@TaskLocal` value carry a request ID into every log line of an upload, and which tasks can read it?

level: middleimportance: should knowfreq 30%

basics

~20 s

Declare @TaskLocal static var requestID: String?, bind it with $requestID.withValue(id) { ... }, and code in that scope reads it like a static property. Child tasks and Task { } inherit the binding; Task.detached reads the default.

open as a page

In Swift 6 language mode, why does a `@MainActor` view model fail to conform to a plain protocol, and what are the fixes, including Swift 6.2's isolated conformances?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A plain protocol requirement can be called from any context, but the class's method may run only on the main actor. Fix it with nonisolated witnesses, a @preconcurrency conformance or, since Swift 6.2, a @MainActor conformance.

open as a page

A Swift `headline(compact:)` function starts `async let air` and returns early without awaiting it; why does that return still take two seconds?

level: seniorimportance: should knowfreq 35%

basics

~20 s

An async let child task cannot outlive its scope. On the early return Swift cancels the unawaited child and then waits for it to finish; cancellation is cooperative, so a child that never checks it runs its full two seconds.

open as a page

A Swift async wrapper around a location SDK sometimes hangs forever and sometimes crashes with SWIFT TASK CONTINUATION MISUSE; what causes each, and how do you fix them?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A continuation must be resumed exactly once. A path that never resumes leaves the caller suspended forever, and CheckedContinuation only logs that leak when its last reference is released; a second resume traps. Resume on every path, then drop the continuation.

open as a page

In Swift 6.2 and later, what changes when a module is built with `-default-isolation MainActor`, and how do you opt code out of it?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Every unannotated declaration in that module is inferred @MainActor instead of nonisolated, so its types become main-actor isolated and Sendable. You opt out per declaration with nonisolated, or with @concurrent for async work that must leave the main actor.

open as a page

In Swift 6 language mode, why does awaiting a non-Sendable RequestLog's async method from the main actor fail, and how does nonisolated(nonsending) fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

By default a nonisolated async method runs off the caller's actor, so calling it from the main actor sends the non-Sendable receiver across a boundary. nonisolated(nonsending), from Swift 6.2, runs it on the caller's actor instead, so nothing is sent.

open as a page

In Swift, what does declaring a ResponseCache class `@unchecked Sendable` actually change, and when is that a safe choice?

level: seniorimportance: should knowfreq 55%

basics

~20 s

@unchecked Sendable only switches off the compiler's Sendable checks for that type; it adds no lock and no run-time check. It is safe only when the type itself guards every access to its mutable state, for example with a lock or Mutex.

open as a page

A Swift chat client feeds messages and presence updates into AsyncStreams; which buffering policy suits each, and what does yield report when the buffer fills?

level: seniorimportance: should knowfreq 35%

basics

~20 s

yield(_:) never waits, so the policy decides what a lagging reader loses: .unbounded keeps all, .bufferingNewest(n) evicts the oldest, .bufferingOldest(n) rejects the newcomer. Messages need every element; presence needs .bufferingNewest(1). yield returns .enqueued, .dropped or .terminated.

open as a page

A Swift chat screen breaks out of its for await loop, yet the socket behind the AsyncStream stays open; when does onTermination actually run?

level: seniorimportance: should knowfreq 35%

basics

~20 s

onTermination runs once: with .finished when the producer calls finish, and with .cancelled when the reading task is cancelled or the stream and its iterators are released. break only drops the iterator, so a stream stored elsewhere stays open.

open as a page

In Swift, how would you upload 50 photos with `withThrowingTaskGroup` keeping at most four in flight, and what happens when one upload throws?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A Swift task group has no width limit: add four uploads, then one more each time next() returns. A child's error surfaces at next(); letting it escape cancels the other children, which the group awaits before rethrowing.

open as a page

showing 1–30 of 33