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?
answer
- a per-module default
- unannotated means main actor
- imported modules keep their own
- nonisolated and @concurrent opt out
- protocols inheriting SendableMetatype
basics
~20 sEvery 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.
solid answer
~40 sSE-0466 (Swift 6.2) lets a module choose its default isolation: `-default-isolation MainActor` for `swiftc`, or `.defaultIsolation(MainActor.self)` as a SwiftPM target setting. Unannotated functions, classes, structs, globals and static properties are then inferred `@MainActor`, which removes most false positives in single-threaded app code: main-actor classes are `Sendable`, and a mutable global is no longer "nonisolated global shared mutable state". `Task { }` inherits the main actor; `Task.detached` does not. Explicit isolation, isolation inherited from a superclass or protocol, actor members and types conforming directly to a protocol that inherits `SendableMetatype`, such as `CodingKey`, keep their own. Opt out with `nonisolated` on a member, type or extension, or `@concurrent` on an async function. Imported modules keep their own default.
code
swift · 26 lines// Built with -swift-version 6 -default-isolation MainActor.
final class FeedStore { // inferred @MainActor
var items: [String] = []
func append(_ item: String) { items.append(item) }
nonisolated func parse(_ raw: String) -> [String] {
raw.split(separator: ",").map(String.init)
}
}
@concurrent
func checksum(_ bytes: [UInt8]) async -> Int { // runs off the main actor
bytes.reduce(0) { $0 &+ Int($1) }
}
func load(into store: FeedStore) async { // inferred @MainActor
Task { // inherits the main actor
store.append("first")
}
Task.detached { // not main-actor isolated
print(store.parse("a,b")) // OK: nonisolated member
}
let sum = await checksum([1, 2, 3])
store.append("sum \(sum)")
}go deeper
Recall that a module can make all its code main-actor isolated by default, and that nonisolated marks the exceptions.
Explain what becomes @MainActor, why that makes model classes Sendable, and which declarations keep their own isolation.
Diagnose work stuck on the main actor in such a module and move it with @concurrent, knowing Task { } inherits the main actor.
Decide module by module: main-actor default for app and UI targets, nonisolated and Sendable design for shared libraries.
## The problem it addresses In Swift 6 language mode the default isolation of an unannotated declaration is **nonisolated**: the compiler assumes any function may be called from any concurrency domain. For an app target where nearly everything runs on the main thread, that presumption of concurrency produces errors about code that is never actually concurrent: mutable globals, non-`Sendable` model classes captured by tasks, main-actor types conforming to nonisolated protocols. **SE-0466**, implemented in **Swift 6.2**, lets a module say "single-threaded by default" instead. ## Turning it on - Compiler flag: `-default-isolation MainActor` (the only other value is `nonisolated`, the default). - Swift package target: `swiftSettings: [.defaultIsolation(MainActor.self)]`; `nil` means nonisolated. - It is **per module**: code imported from other modules keeps whatever default those modules were built with. - It works in Swift 5 and Swift 6 language modes alike, and it is a source-incompatible change, so an existing module keeps the nonisolated default unless it opts in. ## What becomes `@MainActor` With the setting on, an unannotated declaration is inferred `@MainActor`: - global and top-level functions, global variables and static properties; - classes, structs and enums, with their initializers, `deinit`, methods and nested types; - closures follow their context as before, so a non-`@Sendable` closure or a `Task { }` body written inside main-actor code is main-actor isolated. Consequences worth naming: 1. A `final class FeedStore` with mutable `var` properties is now **`Sendable`**, because it is main-actor isolated, so passing it to a `Task.detached` or another actor compiles; touching its state from there needs `await`. 2. A mutable global such as `var requestCount = 0` stops being an error, because it is isolated to the main actor. 3. Calls from nonisolated code into the module's main-actor declarations now need `await`; members marked `nonisolated` do not. ## What keeps its own isolation The default does not override isolation that comes from somewhere else: | Declaration | Isolation with `-default-isolation MainActor` | |---|---| | explicitly annotated (`nonisolated`, `@MainActor`, another global actor) | as written | | inherited from a superclass, overridden method or protocol conformance | inherited | | any member of an `actor` type | the actor's own rules | | type whose primary declaration conforms directly to a protocol that inherits `SendableMetatype` (for example `CodingKey`, through `Sendable`) | nonisolated | | type nested inside a nonisolated type | nonisolated | | typealiases, imports, enum cases | not isolatable | The `SendableMetatype` rule exists because such protocols can only be satisfied by nonisolated conformances; without it, every `CodingKeys` enum would fail to compile. ## Opting out - **`nonisolated`** on a function, property, type or extension (allowed on types and extensions since Swift 6.1, SE-0449) makes it callable from anywhere, with the usual checks. - **`@concurrent`** on an async function (Swift 6.2) makes it nonisolated and always run on the global concurrent executor: the tool for parsing, decoding or hashing that must not block the main actor. Its arguments then cross a boundary, so non-`Sendable` ones must be values the caller gives up. - `Task.detached` starts nonisolated work, but cannot touch main-actor state without `await`. Wrapping work in `Task { }` does **not** opt out: that task inherits the main actor from its context. ## How it interacts with the Sendable rules - Main-actor isolated types are `Sendable`, so most "capture of non-Sendable type" and "sending risks causing data races" errors inside the module disappear: values no longer cross a boundary, or cross it as `Sendable` references. - A `nonisolated` member of a main-actor class cannot touch the class's main-actor state such as its `var` properties ("main actor-isolated property 'items' can not be referenced from a nonisolated context"); it can still read `let` properties of `Sendable` type. - Values passed into a `@concurrent` function from main-actor code are crossing a boundary, so a non-`Sendable` argument must be a disconnected value the caller never touches again; passing one the main actor still holds is rejected as a send that "risks causing data races". - Nothing changes for imported types: a non-`Sendable` class from another module is still non-`Sendable` here. ## Where it fits and where it does not - It suits **app and UI modules** whose code mostly runs on the main thread anyway. - It suits **library and package modules** poorly: their types are used from many isolation domains, and making them main-actor isolated forces every caller onto the main actor. Keep those nonisolated and design them `Sendable`. - It hides nothing: work that was slow on the main thread is still slow; the setting only changes what the compiler assumes, so heavy work still needs an explicit `@concurrent` or nonisolated home.
- With main-actor default isolation, why does a Codable model's synthesized CodingKeys enum still compile?`CodingKey` inherits `Sendable`, which inherits `SendableMetatype`. SE-0466 excludes a type whose primary declaration conforms directly to such a protocol, so the `CodingKeys` enum stays nonisolated and can satisfy `CodingKey`'s nonisolated requirements. Without that rule, every hand-written or synthesized key enum would be inferred `@MainActor` and fail to conform.
- In a main-actor-default module, you move JSON decoding into `Task { }` to get it off the main thread. Does it work?No. `Task { }` inherits its context's isolation, and the context is `@MainActor` by default, so the decoding still runs on the main actor. Put the work in a `@concurrent` async function, or a nonisolated one called from `Task.detached`, and pass it `Sendable` input.
- Default MainActor isolation also applies to code imported from other modules.
- The setting requires Swift 6 language mode.
- Wrapping code in Task { } moves it off the main actor in such a module.
- Members of actor types become main-actor isolated too.
- Library packages should adopt main-actor default isolation like apps do.
Assumes Swift 6.4; module-wide default isolation arrived in Swift 6.2 (SE-0466) and applies in Swift 5 and Swift 6 language modes alike.