Menu

Swift 6 Concurrency in Practice: Actors, Reentrancy, Sendable and What's New in 6.2
πŸ“°

Swift 6 Concurrency in Practice: Actors, Reentrancy, Sendable and What's New in 6.2

DEV Community: swiftΒ·Dheerendra ChaturvediΒ·1 day ago
#BOduWXAN
#devtoswift#devto#dev#actor#await
Reading 0:00
15s threshold

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.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.