ConcurrencyMidMCQ

What is an `Actor` and when should you use one?

Test your knowledge:

Explanation & Code

Answer: An actor is a reference type that protects its mutable state from concurrent access. The Swift compiler enforces that only one task accesses the actor's internals at a time.

Code Example:

actor ImageCache {
    private var cache: [URL: UIImage] = [:]

    func image(for url: URL) -> UIImage? {
        cache[url]
    }

    func store(_ image: UIImage, for url: URL) {
        cache[url] = image
    }
}

// Usage — must be awaited from outside the actor
let cache = ImageCache()
let img = await cache.image(for: url)
await cache.store(image, for: url)

Key Points:

  • Use actor for shared mutable state accessed from multiple tasks
  • @MainActor is a global actor that ensures code runs on the main thread
  • Actor methods are automatically async when called from outside

Rate your understanding:

Ready to practice more Concurrency?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.