Swift & Concurrency (50 Qs)•Part 1: Core Language, Memory & Value Types (1 - 10)
What are Actors in Swift and how do they eliminate Data Races?
junior LevelCode ExampleswiftCore Language
In Simple Words:
An actor is a reference type that protects its mutable state through Actor Isolation:
- Only one task can execute code inside an actor instance at any given time.
- All external calls to an actor's methods or properties must use
await, waiting their turn in an orderly queue. - Eliminates race conditions and shared mutable state bugs without manual locks or dispatch queues!
swift
actor BankAccount {
private var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
func getBalance() -> Double {
return balance
}
}