Back to Swift Reference Ask BeeAI
⚡ ConcurrencyAdvancedSwift 5.5+
Actors
Protect mutable state from data races — only one task touches an actor's state at a time.
An actor is a reference type that serializes access to its mutable state. Code outside the actor must await to call its methods.
Use actors for shared caches, counters and services that many tasks talk to concurrently.
actors.swift
1actor ImageCache {
2 private var storage: [URL: Data] = [:]
3
4 func image(for url: URL) async throws -> Data {
5 if let cached = storage[url] { return cached }
6 let (data, _) = try await URLSession.shared.data(from: url)
7 storage[url] = data
8 return data
9 }
10}
11
12let cache = ImageCache()
13// from any async context:
14// let data = try await cache.image(for: someURL)Common pitfalls
- Actor reentrancy: state can change across an await inside an actor method — re-check assumptions after suspension points.
Still unclear? Ask BeeAI about Actors.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Related topics
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans