← Back to Swift Course | Chapter 13: Concurrency | Lesson 3 of 6

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.

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

markup
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)")

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

markup
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)")
Common Mistakes
  1. Trying to access an actor's property or method directly without await; all external access to an actor's state must be asynchronous.
  2. Forgetting an actor's own internal methods can access its properties directly, without await, since they're already running inside the actor's isolation.
  3. Confusing actors with classes; actors specifically serialize access to their mutable state to prevent data races in concurrent code.
Chapter Summary
  • actor declares 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.