Concurrency ยท SWIFT RECIPE

Protect shared state with an actor

Isolate mutable state behind actor methods.

main.swift
actor Counter {
    private var value = 0
    func increment() { value += 1 }
    func current() -> Int { value }
}
let counter = Counter()
await counter.increment()
print(await counter.current())

How it works

Access actor-isolated state through the actor. Calls across isolation domains generally require await. An actor may process other work while a method suspends.

EXPECTED OUTPUT
1

Keep in mind

Actors prevent many data races, but do not automatically make multi-step operations atomic.

Read the Swift language reference