iOS Developer interview question
When do you use actors in Swift?
Actors serialise access to their isolated mutable state and prevent data races across concurrency domains; crossing an actor boundary requires await, but actors do not make multi-step workflows automatically atomic.
Direct answer
What a strong answer covers
How it works
An actor is a reference type whose mutable state can only be touched from inside the actor, one call at a time; from outside, every method call is asynchronous and requires await, and the compiler rejects synchronous access. That removes data races by construction. Because an await inside an actor method is a suspension point, another call can interleave there, so an invariant that spans two awaits must be re-checked after resuming. @MainActor is the actor for UI state. Actors suit shared caches, connection managers, and any object accessed from many tasks; pure value types and single-task objects do not need one.
Example
An ImageCache actor stores a dictionary of downloaded images; ten concurrent tasks calling await cache.image(for: url) never corrupt the dictionary. Because the download itself awaits, two tasks asking for the same URL can both miss and both download, so the actor keeps a dictionary of in-flight Tasks and returns the existing one.
Common mistakes
- Treating an actor method with multiple awaits as atomic.
- Marking everything @MainActor and serialising background work onto the UI thread.
- Passing non-Sendable class instances across actor boundaries and ignoring the compiler warnings.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.