Actors
An actor is a special kind of type that only lets one piece of code touch its data at a time, so nothing gets mixed up if many things try to use it at once.
In this page:
Declaring and Using an Actor
An actor looks similar to a class but automatically serializes access to its mutable state, requiring await when accessed from outside.
Example: Declaring and Using an Actor
actor Counter {
private var value = 0
func increment() {
value += 1
}
func getValue() -> Int {
return value
}
}
let counter = Counter()
await counter.increment()
await counter.increment()
let current = await counter.getValue()
print("Counter value: \(current)")
Login to try C/C++/Java/PHP code in the editor
Why Actors Prevent Data Races
Because an actor only allows one task to run its methods at a time, concurrent calls to modify its state are automatically serialized, preventing corrupted or inconsistent data.
Example: Why Actors Prevent Data Races
actor BankAccount {
private var balance = 100
func deposit(_ amount: Int) {
balance += amount
}
func currentBalance() -> Int {
return balance
}
}
let account = BankAccount()
await account.deposit(50)
await account.deposit(25)
let balance = await account.currentBalance()
print("Balance: \(balance)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to access an actor's property or method directly without
await; all external access to an actor's state must be asynchronous. - Forgetting an actor's own internal methods can access its properties directly, without
await, since they're already running inside the actor's isolation. - Confusing actors with classes; actors specifically serialize access to their mutable state to prevent data races in concurrent code.
Chapter Summary
actordeclares a reference type that protects its mutable state from concurrent data races.- Access to an actor's properties and methods from outside requires
await. - Code running inside the actor's own methods can access its state directly, without
await. - Actors are Swift's built-in solution for safe concurrent state, replacing manual locks.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: