Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Actors and Data Isolation

Swift Actors and Data Isolation

When multiple tasks modify the same data at the same time, a data race occurs: two tasks both read the old value, each add one, and the result increases only once.

The traditional solution is locking, but locks are easy to forget and prone to deadlock, and the compiler cannot help.

Swift uses actors (SE-0306, introduced in Swift 5.5) to make "this state can only be accessed serially" part of the type system, checked by the compiler.


Why actors are needed

First, look at the problem itself. The class below has no protection, and concurrent calls from multiple tasks overwrite each other.

Even a single += 1 is not an atomic operation: the three steps of reading the value, adding one, and writing it back can be interrupted.

Swift's concurrency checks flag this kind of shared mutable state problem at compile time, and actors are the provided solution.

Approach Who guarantees safety Main risk
No protection No one, relies on self-discipline Data races, unpredictable results
Manual locking Developers, relying on discipline Missed locks, deadlocks, improper lock granularity
actor Compiler checks Syntax overhead of await in usage

Actor definitions and isolated state

An actor is written much like a class, except that its mutable state is isolated by default.

Isolation means outside code cannot directly read or write these properties; they can only be accessed through the actor's own methods.

Defining an actor

The counter below makes value private and exposes only two methods.

Example

import Foundation

actor Counter

{

   

private

var value

=

0

       

// Isolated state, not directly accessible from outside

    func increment

(

)

{

        value

=

1

             

// Can be freely read and written inside the actor

   

}

    func current

(

)

Int

{

       

return

value

   

}

}

// Serial access

let counter

=

Counter

(

)

await counter.

increment

(

)

await counter.

increment

(

)

print

(

await counter.

current

(

)

)

// Concurrent access: 100 tasks incrementing at once, the actor queues them

let shared

=

Counter

(

)

await withTaskGroup

(

of

:

Void.

self

)

{

group in

   

for

_ in

1

...

100

{

        group.

addTask

{

await shared.

increment

(

)

}

   

}

}

print

(

await shared.

current

(

)

)

Running result:



2

100

When 100 tasks concurrently call increment(), the result is exactly 100, because the actor guarantees that only one task at a time executes its isolated code.

An actor is a reference type, passed by reference like a class. Its initializer is not isolated, so Counter() Not required await。

Accessing isolated members with await

To access an actor's isolated properties or methods from outside, you must write await.

This is not optional syntactic sugar; it tells you "there may be a queue wait here".

If the target actor is busy, the call suspends and resumes once it is free.

Access location Whether await is needed Reason
Accessing its own isolated members inside the actor Not required Already inside the isolation domain
Accessing isolated members from outside the actor Needed Crosses isolation domains, may queue
Accessing nonisolated members from outside Not required Does not involve isolated state
Accessing an actor's let constant from outside Not required Immutable and safely shareable

nonisolated

Not all members need isolation protection.

Methods and properties that do not access isolated state can be marked nonisolated so they can be called synchronously from any context without await.

Example

import Foundation

actor Bank

{

   

private

var balance

=

0

    nonisolated let name

=

"RUNOOB Bank"

   

// Does not access isolated state, so it can be marked nonisolated

    nonisolated func describe

(

)

String

{

       

return

"This is (name)'s account"

   

}

    func deposit

(

_ amount

:

Int

)

{

        balance

=

amount

   

}

    func currentBalance

(

)

Int

{

       

return

balance

   

}

}

let bank

=

Bank

(

)

print

(

bank.

name

)

             

// nonisolated, no await needed

print

(

bank.

describe

(

)

)

       

// nonisolated, no await needed

await bank.

deposit

(

100

)

print

(

await bank.

currentBalance

(

)

)

Running result:



RUNOOB 银行

这是 RUNOOB 银行 的账户

100

Both deposit and currentBalance touch balance, so they must remain isolated and require await when called.

nonisolated It only removes isolation and provides no synchronization guarantee. Before marking, confirm the method really does not touch shared mutable state, otherwise you are bypassing the compiler's protection.


Actors vs. locks

Before actors appeared, the common way to protect shared state was locking.

The same counter implemented with NSLock below has the same effect as an actor, but safety relies entirely on the developer.

Example

import Foundation

// @unchecked Sendable means "I guarantee it is thread-safe", and the compiler no longer checks

final

class

LockedCounter

:

@unchecked Sendable

{

   

private

let lock

=

NSLock

(

)

   

private

var value

=

0

    func increment

(

)

{

        lock.

lock

(

)

        value

=

1

        lock.

unlock

(

)

   

}

    func current

(

)

Int

{

        lock.

lock

(

)

        defer

{

lock.

unlock

(

)

}

 

// Use defer to guarantee unlocking

       

return

value

   

}

}

let locked

=

LockedCounter

(

)

await withTaskGroup

(

of

:

Void.

self

)

{

group in

   

for

_ in

1

...

100

{

        group.

addTask

{

locked.

increment

(

)

}

   

}

}

print

(

locked.

current

(

)

)

Running result:



100

The result is the same; the difference lies in cost and guarantees.

Comparison Item Manual locking actor
Who checks Developers, the compiler is not involved The compiler enforces isolation
Consequence of missed protection Data races appear silently Compile-time error
Deadlock risk Yes, especially dangerous when multiple locks interleave No traditional deadlock, but state issues caused by reentrancy
How to call Synchronous calls Cross-isolation access requires await
Can a lock be held across await No, it would block the entire thread Naturally inapplicable; isolation relies on serial execution rather than holding locks

NSLock is "non-recursive"; repeatedly locking on the same thread causes deadlock. Use defer to unlock is the most basic discipline, but missing a single early return can cause a permanent deadlock.


GlobalActor and @MainActor

Sometimes you need multiple types and methods to share the same isolation domain; in that case you can define a global actor.

When an actor is decorated with @globalActor, it becomes an isolation marker that can be attached to any declaration (SE-0316, introduced in Swift 5.5).

Example

import Foundation

// Defining a global actor: shared is a required static property

@globalActor

actor RunoobActor

{

   

static

let shared

=

RunoobActor

(

)

}

@RunoobActor

func runoobTask

(

)

{

    print

(

"Executing on a custom global actor"

)

}

@MainActor

final

class

UIState

{

    var text

=

"Not loaded"

    func update

(

_ newText

:

String

)

{

        text

=

newText

        print

(

"UI text: (text)"

)

   

}

}

await runoobTask

(

)

func demoUI

(

)

async

{

    let state

=

await UIState

(

)

    await state.

update

(

"RUNOOB ready"

)

}

await demoUI

(

)

Running result:



在自定义全局 actor 上执行

界面文字:RUNOOB 已就绪

@MainActor is the global actor provided by the standard library, corresponding to the main thread.

UIKit and SwiftUI UI updates must happen on the main thread, so view models are usually marked entirely as @MainActor.

Marking @MainActor does not mean you can freely write time-consuming operations. It only guarantees execution on the main thread; blocking the main thread will still freeze the UI.


Reentrancy and state consistency

An easily overlooked detail of an actor's serial execution is that await is a reentrancy point.

When a method inside an actor reaches an await and suspends, the actor can handle other calls and return once the suspension ends.

This means "between two awaits, the isolated state may already have been changed by someone else".

Example

import Foundation

actor Loader

{

   

private

var cache

:

[

String

:

String

]

=

[

:

]

    func load

(

_ key

:

String

)

async

String

{

       

if

let cached

=

cache

[

key

]

{

           

return

cached

       

}

       

// This await is a reentrancy point: other calls can enter during suspension

       

try

?

await Task.

sleep

(

for

:

.

milliseconds

(

10

)

)

        let value

=

"Data for (key)"

        cache

[

key

]

=

value

       

return

value

   

}

}

let loader

=

Loader

(

)

print

(

await loader.

load

(

"runoob"

)

)

print

(

await loader.

load

(

"runoob"

)

)

Running result:



runoob 的数据

runoob 的数据

The second call hits the cache and returns directly without running the wait logic again.

But there is a hidden risk here: if two calls arrive almost simultaneously, both will find the cache empty, then each suspend, each compute, and each write, duplicating work.

When you need "load only once" semantics, put "check the cache" and "mark as loading" in the same non-suspending step.

Remember this rule:await A condition that held beforeawait may not necessarily still hold after. State assumptions across awaits are the most common source of bugs in actor code.


Common questions

Below are some of the most common pitfalls when using actors.

Can actor methods be called directly

Isolated methods cannot; they require await. Methods marked nonisolated can.

An actor's initializer is not isolated, so creating an instance does not require await.

Can actors be inherited

No. Actors do not support inheritance and cannot be inherited by classes.

When you need to share behavior, use protocols plus extensions for reuse.

Can actor properties be marked willSet / didSet

No. Property observers require controllable read/write paths, while an actor's isolated access is asynchronous; the two are incompatible.

Can properties in an actor be declared as let

Yes, and constants are immutable by nature, so accessing them from outside does not require await.

What is the difference between an actor and @MainActor

A regular actor is an independent instance, each with its own isolation domain.

@MainActor is a global actor; all code marked with it shares the same isolation domain, which is bound to the main thread.

When to use an actor

When a piece of mutable state will be accessed by multiple concurrent tasks, using an actor is the most worry-free choice.

If the state is used only in a single task, or is immutable, you don't need an actor; adding one only brings unnecessary awaits.