Hi everyone π
After my mTLS post, I wanted to write up what I've learned about actors and the concurrency model in Swift 6: how they work, the mistakes I made along the way, and what changed in Swift 6.2. Corrections are very welcome!
1. What an actor gives you
An actor is a reference type that protects its own mutable state. Only one task runs on an actor at a time, so the compiler can prove there are no data races. Code outside the actor has to await to reach that state.
enum BankError : Error { case insufficientFunds }
actor BankAccount { private ( set ) var balance : Decimal = 0
func deposit ( _ amount : Decimal ) { balance += amount }
func withdraw ( _ amount : Decimal ) throws { guard balance >= amount else { throw BankError . insufficientFunds } balance -= amount } }
let account = BankAccount ( ) await account . deposit ( 100 ) let current = await account . balance
Enter fullscreen mode
Exit fullscreen mode
Inside the actor, calls are synchronous.β¦