
With the rise of Swift Concurrency, managing shared mutable state without data races became critical. Enter the actor type—Swift’s modern solution for isolated, thread-safe state without the complexity of locks or GCD queues.
What is an Actor?
An actor is like a class, but with internal data isolation. Only one task can interact with its mutable state at a time. This eliminates data races by default:
actor Counter {
private var value = 0
func increment() {
value += 1
}
func getValue() -> Int {
value
}
}
By design, actors serialize access to their mutable state—even when accessed from multiple concurrent tasks. This gives you the safety of locks without ever writing one.
Accessing Actor Methods
Since actor methods may be called from outside their isolation domain, Swift requires await:
let counter = Counter()
await counter.increment()
let current = await counter.getValue()
Actor-isolated functions must be async, unless they’re marked nonisolated or are accessing immutable state only.
When to Use Actors
• You need to share mutable state safely across tasks
• You’re building services like caches, analytics trackers, sync engines
• You want lightweight, structured thread-safety
Avoid actors for performance-critical code where high-throughput sync access is required, or for modeling value types (use struct).
