Default MainActor isolation and nonisolated(nonsending) in practice (Swift 6.2)

This continues my "…in Practice" series. In the earlier actors post I converted a view model and a cache to explicit @MainActor, and most of the time went into chasing Sendable errors and adding MainActor.run hops. Swift 6.2's Approachable Concurrency settings aim to remove most of that: you declare a module main-actor by default, and most of the annotations go away.

I wanted to see what that does to real code: where behaviour changes without any warning, and which diagnostics show up along the way. So I wrote the same small app layer twice, once the old way and once migrated, and noted every compiler error.

Every snippet below comes from a package that builds with swift build -c release with zero warnings and whose tests pass (7 tests, 2 suites).

Toolchain: Apple Swift 6.2.4 (swiftlang-6.2.4.1.4 clang-1700.6.4.2), Xcode 26.3 (17C529), macOS 15.7.4, x86_64. Swift 6 language mode throughout.

The setup

Two SwiftPM targets hold the same code: a Product model, a URLSession repository, an image cache, a view model and a delegate-style protocol conformance. LegacyApp is written the pre-6.2 way. ModernApp turns on three settings:

.target(
    name: "ModernApp",
    swiftSettings: [
        .defaultIsolation(MainActor.self),                        // SE-0466
        .enableUpcomingFeature("NonisolatedNonsendingByDefault"), // SE-0461
        .enableUpcomingFeature("InferIsolatedConformances"),      // SE-0470
        .swiftLanguageMode(.v6),
    ]
),

All three are implemented in 6.2.4. In Xcode, the closest equivalents are the Default Actor Isolation = MainActor build setting plus Approachable Concurrency = Yes. The second turns on a group of upcoming features that includes the two above. If you're in Xcode, check the exact feature list for your version.

What default MainActor isolation actually changes

It makes unannotated declarations main-actor-isolated. That includes types and methods, and also free functions, globals and protocols. The cache goes from this:

@MainActor
public final class ImageCache {
    private var storage: [URL: Data] = [:]
    public init() {}
    public func image(for url: URL) -> Data? { storage[url] }
    public func insert(_ data: Data, for url: URL) { storage[url] = data }
}

to the same class without the attribute. It reads like an ordinary class, but it is fully isolated.

What surprised me was how far "unannotated" reaches. A small free helper that checks the current thread had to be marked nonisolated, or nothing off the main actor could call it:

// Under default isolation even a free function is MainActor-isolated,
// so this must be `nonisolated` to be callable from off-main code.
public nonisolated func isOnMainThread() -> Bool {
    pthread_main_np() != 0
}

Without the annotation:

error: main actor-isolated global function 'isOnMainThread()' cannot be
called from outside of the actor

That's the change in mental model: under default isolation you stop marking the things that are on the main actor and start marking the things that aren't.

The same applies to protocols. My delegate protocol needed nonisolated protocol RefreshObserver, or default isolation would have pulled its requirement onto the main actor too.

nonisolated(nonsending) vs @concurrent

This is where behaviour changes silently. It comes from SE-0461.

  • Before: a nonisolated async function never runs on its caller's actor. It starts on the generic (global concurrent) executor, so calling it from the main actor means a hop off the main actor and a hop back.
  • With NonisolatedNonsendingByDefault: a plain nonisolated async function runs on the caller's executor. It inherits the caller's isolation instead of leaving it. If you want the old "get off the actor" behaviour, you now ask for it explicitly with @concurrent.

My repository uses both. fetchProducts should stay with its caller, and decode is the one piece I actually want off the main actor:

public final class ProductRepository {          // MainActor by default
    let session: URLSession

    public nonisolated(nonsending) func fetchProducts(from url: URL) async throws -> [Product] {
        let (data, _) = try await session.data(from: url)
        return try await decode(data)
    }

    @concurrent public func decode(_ data: Data) async throws -> [Product] {
        try JSONDecoder().decode([Product].self, from: data)
    }
}

With the feature on, writing nonisolated(nonsending) explicitly is redundant, since a plain nonisolated func … async already behaves that way. I keep the explicit spelling in the post because it says what's happening at a glance, and it stays correct if the file is ever compiled without the flag.

Proving where it runs

A test calls a method with the same shape on both modules from the main actor and checks whether the body ran on the main thread:

@MainActor
@Suite("Where the code runs")
struct IsolationTests {
    @Test("nonisolated async hops off-main; nonisolated(nonsending) stays on the caller")
    func silentExecutorChange() async {
        let legacy = LegacyApp.ProductRepository()
        let modern = ModernApp.ProductRepository()

        let legacyRanOnMain = await legacy.ranOnMainThread()
        let modernRanOnMain = await modern.ranOnMainThread()

        #expect(legacyRanOnMain == false)
        #expect(modernRanOnMain == true)
    }
}
Called from the main actor Legacy module Modern module
nonisolated func f() async generic executor (off-main) caller's executor (main)
nonisolated(nonsending) func f() async (not used) caller's executor (main)
@concurrent func f() async (not used) generic executor (off-main)

A caveat on what this test proves. pthread_main_np() is a proxy. The modern result is true only because the caller is the main actor. Call the same nonisolated(nonsending) function from a different actor and it runs on that actor's executor, off the main thread. The rule is "execution follows the caller", not "always main". (Thread.isMainThread isn't an option here. See the diagnostics section.)

Nothing at the call site shows that anything changed. Code that used to run off the main thread now runs on it after you turn on the flag. For UI-adjacent code that's usually what you want. For a CPU-heavy function you relied on to offload work, it's a regression you'll only catch with an isolation check or a profiler.

Isolated conformances and the Codable edge case

InferIsolatedConformances (SE-0470) lets a main-actor type satisfy a nonisolated protocol requirement with a main-actor method. The conformance itself becomes main-actor-isolated. My delegate loses the old nonisolated + Task bounce:

// Legacy: must be nonisolated, so it bounces through a Task
public nonisolated func didRefresh(count: Int) {
    Task { @MainActor in self.lastCount = count }   // not set yet when this returns
}

// Modern: isolated conformance, touches main-actor state directly
public func didRefresh(count: Int) { lastCount = count }   // set synchronously

The test can check lastCount straight after the call, with no awaiting a detached task.

The catch is Codable. An isolated conformance can only be used on the main actor, and decoding is exactly the kind of work you push off it. My Settings type is a class with a custom init(from:). Left unannotated, the class, its initializer and the inferred Decodable conformance are all main-actor-isolated. Decoding it from an @concurrent function fails:

error: main actor-isolated conformance of 'Settings' to 'Decodable'
cannot be used in nonisolated context [#IsolatedConformances]

My first instinct was to mark only the conformance nonisolated. That fails with a different diagnostic, because the initializer is still isolated:

error: conformance of 'Settings' to protocol 'Decodable' crosses into
main actor-isolated code and can cause data races [#ConformanceIsolation]
note: main actor-isolated initializer 'init(from:)' cannot satisfy
nonisolated requirement

The fix that works is to opt the whole type out, which makes init(from:) nonisolated too:

public nonisolated final class Settings: Codable {
    public var fontScale: Int
    public required init(from decoder: Decoder) throws { … }
    public func encode(to encoder: Encoder) throws { … }
}

I did the same for the Product struct, because the @concurrent decode above needs a nonisolated Decodable conformance for [Product]:

public nonisolated struct Product: Codable, Identifiable, Sendable, Equatable { … }

The rule I ended up with: any model or DTO that is decoded, encoded or sent across actors gets nonisolated. It's one keyword, it documents intent, and it keeps the conformance usable anywhere.

The migration, step by step

  1. Add the settings to one target and build. The first wave of errors is "cannot be called from outside of the actor" on helpers and free functions. Mark the ones that really are shared nonisolated.

  2. Mark models, DTOs and delegate protocols nonisolated.

  3. Delete @MainActor from view models, caches and UI types. They're already isolated.

  4. Replace Task.detached + MainActor.run with one awaited @concurrent call. The legacy two-hop version:

    public func loadInBackground(_ data: Data) {
        let repository = self.repository
        Task.detached {
            let decoded = (try? repository.decode(data)) ?? []
            await MainActor.run { self.products = decoded }
        }
    }
    

    becomes:

    public func loadInBackground(_ data: Data) async {
        products = (try? await repository.decode(data)) ?? []
    }
    

    This is also a semantic improvement, not just shorter code. The old version was fire-and-forget, so a caller (or a test) had no way to know when products was updated. The new one can be awaited, and the result lands back on the main actor automatically.

  5. Go through every nonisolated async function and decide: should it stay with its caller (leave it as is, now nonsending by default), or offload work (@concurrent)? This is the one decision the feature makes you take deliberately.

Diagnostics I hit, and the fixes

  • class property 'isMainThread' is unavailable from asynchronous contexts (and the same for Thread.current). Foundation marks both unavailable from async code on purpose, because "which thread am I on" is the wrong question under Swift concurrency. I used pthread_main_np() for the demonstration only.
  • error: expected declaration on public @concurrent func. The attribute has to come before the access modifier: @concurrent public func.
  • #expect(ModernApp.isOnMainThread()) fails to expand. When two imported modules export the same free function, the module-qualified call didn't expand inside #expect. Binding the result to a local first works. That's a macro limitation, not a concurrency one, but you'll hit it in exactly this kind of before/after test.
  • [#IsolatedConformances] and [#ConformanceIsolation], covered above.

How they compare

Legacy pattern Modern pattern
Main-actor type @MainActor final class unannotated (default)
Async work that stays on the caller only via an isolated parameter (e.g. #isolation) nonisolated async (nonsending by default)
Offload work Task.detached + MainActor.run @concurrent func, awaited
Delegate conformance nonisolated method + Task hop isolated conformance, direct
Codable DTO nonisolated implicitly must be marked nonisolated
Sendable pressure high: every hop crosses actors lower: fewer crossings

Pitfalls and limitations

  • The nonsending default is a silent runtime change. Before turning on the flag, audit anything you relied on to run off the main actor.
  • Models get pulled onto the main actor. Under default isolation an unannotated DTO is main-actor-isolated, and so is its Codable conformance. Mark them nonisolated early.
  • There's no Bool "am I on the main actor?" check. MainActor.assertIsolated() / preconditionIsolated() trap rather than return a value, which is awkward inside #expect. pthread_main_np() is a test-only proxy, not an isolation check.
  • Default isolation is per target. You migrate a package one target at a time. The boundaries between migrated and unmigrated targets are where the remaining Sendable work sits.

Migration tips

  • Turn the settings on one target at a time, and read every error before you fix it. Several of them point at an offload you were doing by accident.
  • Mark shared helpers, DTOs and delegate protocols nonisolated first, then delete @MainActor from the top down.
  • Treat every remaining @concurrent as a design decision and leave a one-line comment on why it offloads.

Not covered here

sending parameters and results, isolated parameters / #isolation, actor reentrancy (covered in the earlier post), and examples that cross module boundaries between a migrated and an unmigrated target. Linux is also untested. The package has a Glibc branch for the thread check, but I haven't run it. No performance numbers are claimed anywhere: the offload benefit of @concurrent is structural, not measured.

Open questions for the thread

  1. Is there a supported, non-trapping way to check "am I on the main actor?" at runtime (one that returns a Bool), or is a pthread_main_np()-style proxy the best option for tests today?
  2. For a synthesized-Codable Sendable struct under default MainActor isolation, what exactly is the inference rule? Is nonisolated always needed to use the conformance from an @concurrent function, or are there cases where the conformance is already nonisolated? I marked mine explicitly and would like to know whether that's necessary or just tidy.
  3. With NonisolatedNonsendingByDefault, is there a recommended lint or audit for finding functions that used to offload work and now silently run on the caller?

Really useful write-up, thanks for doing the side-by-side comparison — that table of where each function actually runs is the clearest explanation of NonisolatedNonsendingByDefault I've seen.

On your first question: as far as I know there still isn't a public, non-trapping Bool check for "am I on the main actor?". MainActor.assertIsolated traps by design, and Thread.isMainThread is unavailable from async contexts for exactly the reason you ran into. For tests, your pthread_main_np proxy is the pragmatic option — just with the caveat you already noted, that it proves main thread, not main actor, so it only holds when the caller is the main actor.

On the third question, I don't know of a recommended lint either, and I agree that's the scariest part of the migration. The only audit that's worked for me is a plain grep for nonisolated async functions, then going through each one and deciding deliberately whether it stays with the caller or gets @concurrent. It's tedious, but it's the one place where the compiler genuinely can't help you, since the code is still correct — it just runs somewhere different now. Your tip about leaving a one-line comment on every @concurrent is a good one; six months later that's the only thing that explains why it offloads.