Why actors prevent data races
📖 Scenario: Imagine you have a shared bank account accessed by multiple people at the same time. Without rules, two people might try to withdraw money simultaneously, causing errors. In Swift, actors help manage this by making sure only one person accesses the account at a time, preventing mistakes called data races.
🎯 Goal: You will create a simple BankAccount actor that safely updates the balance. You will then try to update the balance from multiple tasks and see how actors prevent data races.
📋 What You'll Learn
Create an actor called
BankAccount with a balance property set to 100Add a function
withdraw(amount:) inside the actor to subtract from balanceCreate a constant
account as an instance of BankAccountCall
withdraw(amount: 30) twice concurrently using TaskPrint the final
balance after both withdrawals💡 Why This Matters
🌍 Real World
Actors are used in apps where multiple parts of the program need to safely share and update data, like bank apps, games, or messaging apps.
💼 Career
Understanding actors and data race prevention is important for Swift developers working on safe, concurrent applications.
Progress0 / 4 steps