In Swift, what does marking a view model class `@MainActor` guarantee, and how does background work hand its results back to it?
answer
- an actor named by an attribute
- every member isolated to one actor
- await to hop onto it
- 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@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
Recall that @MainActor isolates a type's members to the main actor, and that code elsewhere reaches them with await or a @MainActor closure.
Explain global actors, which members the attribute covers, and where an awaited nonisolated async function runs inside an isolated method.
Pick the right hand-off for each case, explain why assumeIsolated traps instead of hopping, and spot reentrancy in overlapping reload calls.
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.