Actors & data isolation, nonisolated
Learn actor isolation: state is protected behind an actor , cross-actor access requires await , and nonisolated members bypass isolation when they are pure or static.
What actors provide
An actor protects its mutable state. Only one task touches isolated state at a time; external callers must await its methods.
- Isolation = no data races
- Cross-actor calls are async
- nonisolated for pure/static members
Actor basics
Inside the actor, access is direct. From outside, you must await both reads and writes of isolated state.
actor Counter {
private var value: Int = 0 // isolated state
func increment() { value += 1 } // isolated method (async to outsiders)
func get() -> Int { value } // read isolated state
}
let c = Counter()
Task {
await c.increment()
print(await c.get()) // 1
}All lessons in this course
- TaskGroup for parallelism
- Actors & data isolation, nonisolated
- Sendable and thread-safety checking