skip to content

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%

answer

  1. opting a member out of isolation
  2. callable from anywhere without await
  3. only immutable Sendable state
  4. a parameter that names the actor

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.

solid answer

~50 s

`nonisolated` opts a declaration out of its actor's isolation. A `nonisolated func` or `nonisolated let` can be used from any context without `await`, which is how an actor satisfies a synchronous protocol requirement such as `hash(into:)`. The price is that the body counts as outside code: it may read `let` properties of `Sendable` type, but touching mutable state fails with "actor-isolated property 'hits' can not be referenced from a nonisolated context", and `nonisolated` cannot be applied to a mutable stored property at all. An `isolated` parameter works the other way: `func prewarm(_ cache: isolated ThumbnailCache)` is isolated to whichever cache is passed, so its body calls that actor's members synchronously and callers pay one `await` to enter. Swift 6.0's `#isolation` macro, as the default of an `isolated (any Actor)?` parameter, lets a helper run on its caller's actor.

code

swift · 25 lines
swift
actor ThumbnailCache {
    nonisolated let namespace: String
    private var hits = 0

    init(namespace: String) { self.namespace = namespace }

    nonisolated func key(for name: String) -> String {
        "\(namespace)/\(name)"            // immutable Sendable state only
    }

    func recordHit() { hits += 1 }
}

// Runs on whichever ThumbnailCache is passed in: no await inside.
func prewarm(_ cache: isolated ThumbnailCache, names: [String]) {
    for _ in names { cache.recordHit() }
}

func label(for cache: ThumbnailCache) -> String {
    cache.key(for: "cat")                 // synchronous, from anywhere
}

func warmUp(_ cache: ThumbnailCache) async {
    await prewarm(cache, names: ["cat", "dog"]) // one hop, two hits
}

go deeper

for a junior

Recall that nonisolated lets an actor member be used without await, and that such a member cannot touch the actor's mutable state.

for a middle

Explain which properties a nonisolated member may read, why synchronous protocol requirements need it, and what an isolated parameter changes.

for a senior

Use isolated parameters to batch work into one hop and #isolation to keep a helper on its caller's actor in Swift 6 mode.

for a principal

Judge when nonisolated surface on an actor is a design smell that shows state should be immutable, split out or not an actor at all.

## Isolation is the default inside an actor Every instance property, method and subscript declared in an actor, or in an extension of it, is **isolated** to the actor instance `self`: it touches the actor's state synchronously and can be reached from outside only through an asynchronous call. Two modifiers let a declaration choose differently. SE-0313, "Improved control over actor isolation", introduced both in Swift 5.5. ## `nonisolated`: stepping outside the actor A `nonisolated` member is treated as if it were written outside the actor: - it can be called or read **synchronously from any context**, with no `await`; - it may use the actor's `let` properties of `Sendable` type, and call other nonisolated members; - it may **not** read or write isolated mutable state; a synchronous `nonisolated func` that touches `var hits` fails with "actor-isolated property 'hits' can not be referenced from a nonisolated context", or "can not be mutated" for a write; - a `nonisolated async func` may still reach isolated state, but only through `await`, like any outside caller. On stored properties the rules are tight. `nonisolated let` is allowed; in Swift 6 language mode its type must be `Sendable`, or the compiler reports "'nonisolated' can not be applied to variable with non-'Sendable' type". A mutable stored property is rejected in both modes: "'nonisolated' cannot be applied to mutable stored properties". `nonisolated(unsafe)` exists as an explicit escape hatch that removes checking, and belongs with the unchecked tools of Sendable and data-race safety. Since Swift 6.1 (SE-0449), `nonisolated` can also be written on a type or an extension, which is mostly used to cut off global-actor inference, for example a `nonisolated extension` of a `@MainActor` class. ## Where `nonisolated` is needed Protocols with synchronous requirements are the usual reason. `Hashable` requires `hash(into:)` and `==`, which generic code such as `Set` calls from anywhere. If an actor implements them as isolated methods, Swift 6.4 reports "conformance of 'ThumbnailCache' to protocol 'Hashable' crosses into actor-isolated code and can cause data races", and for an actor this is an error even in Swift 5 language mode. The fix is to make both requirements `nonisolated` and base them on immutable `let` properties of `Sendable` type, which a nonisolated member may read. `CustomStringConvertible.description` follows the same pattern. ## `isolated` parameters: one hop for many operations An `isolated` parameter makes a function isolated to the actor passed in that parameter. Inside, the function uses the actor as if it were `self`: synchronous calls, no `await`. From outside, calling the function is a cross-actor call, so a caller writes one `await` and then every operation inside runs on the actor without further hops. Rules worth knowing: | Rule | Swift 5 mode | Swift 6 mode | |---|---|---| | one `isolated` parameter per function | required | required | | two `isolated` parameters | warning: "cannot have more than one 'isolated' parameter" | error | | `isolated (any Actor)?` | allowed (Swift 6.0 and later) | allowed | In fact, an actor's own methods behave as if `self` were an isolated parameter. ## `#isolation`: inheriting the caller's actor A helper that is generic over who calls it, say a logging or retry function, has a problem: as a plain nonisolated `async` function it runs on the generic executor, so an actor that passes it a non-`Sendable` value sends that value out of its isolation domain. In Swift 6 language mode that is rejected with "sending 'self.log' risks causing data races". Declaring the parameter `isolation: isolated (any Actor)? = #isolation` fixes it: 1. `#isolation` is a macro that expands to the actor the calling code is isolated to, or `nil` for nonisolated code. 2. Because the parameter is `isolated`, the helper runs on that actor. 3. The non-`Sendable` value never leaves the actor's domain, so the call compiles in Swift 6 mode. Swift 6.2's `nonisolated(nonsending)` offers a declaration-level way to get the same effect, covered with Sendable and data-race safety. ## Common mistakes - Marking a method `nonisolated` to "make it faster" and then needing actor state inside it. - Expecting `nonisolated var` to give a lock-free counter. - Thinking an `isolated` parameter runs the function on a background thread; it runs on the given actor.

  • Why does an actor's `Hashable` conformance need `nonisolated` on `hash(into:)` and `==`?
    Both requirements are synchronous and nonisolated, and generic code such as `Set` calls them from any context. An isolated implementation cannot satisfy them, so Swift reports that the conformance "crosses into actor-isolated code and can cause data races", an error for actors in both language modes. Mark both `nonisolated` and base them only on immutable `let` properties of `Sendable` type.
  • Can a Swift function take two `isolated` parameters, for example to move data between two caches?
    No. Code runs on one actor at a time, so a function can be isolated to only one. Swift 6.4 warns "cannot have more than one 'isolated' parameter" in Swift 5 mode and makes it an error in Swift 6 mode. Make the function isolated to one cache and `await` calls on the other.

  • A nonisolated actor method can still update the actor's counters synchronously.
  • nonisolated var gives an actor a lock-free mutable property.
  • An isolated parameter makes the function run on a background thread.
  • #isolation always resolves to the main actor, whoever the caller is.
  • A nonisolated member cannot read any of the actor's properties, even immutable ones.

Assumes Swift 6.4: #isolation with an optional isolated parameter arrived in Swift 6.0 (SE-0420), nonisolated on types and extensions in Swift 6.1 (SE-0449), and two isolated parameters or sending an actor's non-Sendable value to a nonisolated async helper are errors only in Swift 6 language mode.