🍎 Swift & iOS Intermediate

What are Swift actors?

Why Interviewers Ask This

Mid-level Swift & iOS roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Actors (Swift 5.5+) are reference types that protect their mutable state from concurrent access — they serialize access to their methods and properties. Actors eliminate data races without manual locking. Declaring an actor: actor BankAccount { private var balance: Double = 0 func deposit(_ amount: Double) { balance += amount } func withdraw(_ amount: Double) throws { guard balance >= amount else { throw BankError.insufficientFunds } balance -= amount } func getBalance() -> Double { balance } }. Using an actor — must await: let account = BankAccount() // Actor method calls require await: await account.deposit(100) let balance = await account.getBalance() try await account.withdraw(50). How actors prevent data races: only one piece of code can access an actor's internals at a time. Other callers wait. The actor schedules access, preventing concurrent mutation. MainActor: a global actor that ensures all access happens on the main thread: @MainActor class ViewModel: ObservableObject { @Published var text = "" // Automatically on main thread func update() { text = "Updated" // Safe -- on main actor } } // Can also mark individual functions: @MainActor func updateUI() { label.text = "Hello" }. nonisolated: opt out of actor isolation for non-mutating methods: actor DataStore { nonisolated let id = UUID() // No await needed func fetchData() async -> Data { /* ... */ } }. Sendable protocol: types safe to send across concurrency domains. Value types are Sendable by default. Classes need explicit conformance or @unchecked Sendable. Actor vs class: actor = thread-safe reference type; class = not thread-safe reference type.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.