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
actorfor shared mutable state accessed from multiple tasks @MainActoris a global actor that ensures code runs on the main thread- Actor methods are automatically
asyncwhen called from outside
Rate your understanding: