Back to walidsassi.com

Swift Actor Common Pitfall: Parameters Are NOT Protected!

class DownloadCounter { var count = 0 var lastDownload: Date? } actor DownloadManager { private var totalProcessed = 0 // โœ… Protected by actor func processDownload(_ counter: DownloadCounter) async { totalProcessed += 1 // โœ… Safe - actor's state // ๐Ÿ’ฅ DANGER: counter is NOT protected! counter.count += 1 // โŒ Potential data race counter.lastDownload = Date() // โŒ Potential data race } } // Data race scenario func dangerousUsage() async { let counter = DownloadCounter() let manager = DownloadManager() // Thread 1 Task { await manager.processDownload(counter) } // Thread 2 - Concurrent access! Task { counter.count += 5 // ๐Ÿ’ฅ DATA RACE with Thread 1 } } โœ… The Solution: sending to Transfer Ownership ...

August 11, 2025 ยท 1 min ยท Walid Sassi