Profile
Back to NewsBack
Dev.to 8 min
Reader Mode
Default MainActor Isolation and nonisolated(nonsending) in Practice: migrating a real iOS app layer to Approachable Concurrency

Default MainActor Isolation and nonisolated(nonsending) in Practice: migrating a real iOS app layer to Approachable Concurrency

15 hours ago

This continues the "…in Practice" series. In the earlier actors post I converted a view model and a cache to explicit @MainActor and spent most of the time chasing Sendable errors and inserting MainActor.run hops. Swift 6.2's Approachable Concurrency settings are meant to remove most of that ceremony: you declare that a module is main-actor by default, and the annotations mostly disappear. I wanted to see what that actually does to real code, where it changes behavior silently, and which diagnostics you hit on the way. So I built the same small app layer twice — once the old way, once migrated — and read every compiler error out loud.

Everything below is copied from a package that builds with swift build -c release at zero warnings and whose tests pass.

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:

.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 these are bundled behind the "Approachable Concurrency" build setting plus "Default Actor Isolation: MainActor"; the SwiftPM spellings above are the equivalent.

What default MainActor isolation actually changes

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

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

to the same thing without the attribute. It reads like an ordinary class but is fully isolated. The surprise is how far "unannotated" reaches. A free helper that checks the current thread had to be marked nonisolated, or nothing off-main 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
}

Leaving it isolated produced:

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

That is the mental model shift: under default isolation you stop annotating the things that are on the main actor and start annotating the things that are not.

nonisolated(nonsending) vs @concurrent

This is the part that changes behavior silently, and it comes from SE-0461. Before 6.2, a nonisolated async function hops to the global concurrent executor for its awaits. With NonisolatedNonsendingByDefault, a plain nonisolated async function instead runs on the caller's executor — it does not leave the actor that called it. If you want the old "get off the actor" behavior you now ask for it explicitly with @concurrent.

My repository has both. fetchProducts should stay with its caller; decode is the one piece I genuinely want on a background thread:

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)
}

Where an async function runs from the main actor, before and after NonisolatedNonsendingByDefault

Where does each run? A test calls the same-shaped method on both modules from the main actor and asks whether it executed on the main thread (pthread_main_np() as a proxy — Foundation now refuses Thread.isMainThread from async code, more on that below):

Call, from the main actor Legacy module Modern module
nonisolated func f() async global pool (off-main) n/a
nonisolated(nonsending) func f() async n/a caller (main)
@concurrent func f() async global pool global pool

The test asserts exactly this and passes:

let legacyRanOnMain = await legacy.ranOnMainThread()   // false
let modernRanOnMain = await modern.ranOnMainThread()   // true
#expect(legacyRanOnMain == false)
#expect(modernRanOnMain == true)

Nothing at the call site tells you this flipped. Code that used to run off the main thread now runs on it, by default, after you flip the feature flag. For UI-adjacent code that is usually what you want; for a CPU-heavy function you were relying on to offload, it is a regression you will 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 isolated. My delegate shrinks from the old nonisolated + Task bounce:

// Legacy
public nonisolated func didRefresh(count: Int) {
    Task { @MainActor in self.lastCount = count }   // value is not set yet on return
}
// Modern
public func didRefresh(count: Int) { lastCount = count }   // set synchronously

The catch is Codable. This is where default isolation genuinely bit me, and the behavior is more subtle than "Codable breaks." A plain Sendable struct with a synthesized conformance is fine — its conformance stays nonisolated, and it decodes anywhere. But a reference type with a custom init(from:) becomes a problem, because the init is main-actor-isolated and so is the inferred conformance. 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 fix instinct — mark only the conformance nonisolated — is rejected with a different diagnostic, because the init 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 { … }

So the rule I settled on: models and DTOs that cross actors get nonisolated; value types with synthesized Codable usually need nothing.

The migration, step by step

Migration in five steps

  1. Add the three settings to the target. Build. The first wave of errors is "cannot be called from outside of the actor" on helpers and free functions — mark the genuinely-shared ones nonisolated.
  2. Delete @MainActor from the view model, cache, and view types. They are already isolated.
  3. Replace the Task.detached { … } + MainActor.run { … } offload with a single @concurrent function you await. The modern view model is:
public func loadInBackground(_ data: Data) async {
    products = (try? await repository.decode(data)) ?? []
}

versus the legacy two-hop:

public func loadInBackground(_ data: Data) {
    let repository = self.repository
    Task.detached {
        let decoded = (try? repository.decode(data)) ?? []
        await MainActor.run { self.products = decoded }
    }
}
  1. For each nonisolated async function, decide: should it stay with its caller (drop to a plain method, now nonisolated(nonsending) by default) or offload (@concurrent)? This is the one decision the feature forces you to make deliberately.
  2. Fix Codable conformances on reference types with nonisolated.

Diagnostics I hit, and the fixes

  • class property 'isMainThread' is unavailable from asynchronous contexts and class property 'current' is unavailable from asynchronous contexts. Foundation marks Thread.current / Thread.isMainThread NS_SWIFT_UNAVAILABLE_FROM_ASYNC on purpose — the whole point of the migration is that "which thread" is the wrong question. I used pthread_main_np() for the demonstration only.
  • error: expected declaration on public @concurrent func. Attribute ordering: it must be @concurrent public func, attribute before the access modifier.
  • The two #IsolatedConformances / #ConformanceIsolation errors above.

How they compare

Legacy pattern Modern pattern
Main-actor type @MainActor final class unannotated (default)
Stay on caller not expressible without isolated params nonisolated(nonsending) (default for async)
Offload work Task.detached + MainActor.run @concurrent func
Delegate conformance nonisolated method + Task hop isolated conformance, direct
Codable DTO nonisolated anyway nonisolated on reference types with custom init
Sendable pressure high — every hop crosses actors lower — fewer crossings

Pitfalls and limitations

  • The nonisolated(nonsending) default is a silent runtime change. Audit anything you relied on to run off-main before flipping the flag.
  • pthread_main_np() is a proxy for "main actor," not a supported isolation check. For real assertions use MainActor.assertIsolated(); it traps rather than returning a bool, so it is awkward inside #expect.
  • #expect cannot take a module-qualified free-function call directly (#expect(ModernApp.isOnMainThread()) fails to expand) — bind to a local first. This is a macro limitation, not a concurrency one, but you will hit it when two modules export the same symbol.
  • Default isolation is per-target. A package with many targets is migrated one target at a time, and the boundaries between migrated and unmigrated targets are where the remaining Sendable work lives.

Migration tips

  • Turn on one target at a time and read every error before "fixing" it; several are telling you about a real offload you were doing by accident.
  • Start by marking shared helpers and DTOs nonisolated, then delete @MainActor top-down.
  • Treat every surviving @concurrent as a design decision worth a comment.

Open questions for the thread

  1. Is there a supported, non-trapping way to assert "I am on the main actor" at runtime (a Bool), or is pthread_main_np() genuinely the best proxy today?
  2. For a reference type that must be decoded off-main but also holds main-actor UI state, is a nonisolated split DTO the intended pattern, or is there a lighter conformance-only escape I missed?
  3. With NonisolatedNonsendingByDefault, is there a recommended lint or audit to catch functions that used to offload and now silently run on the caller?
Chat with me