0
0
Swiftprogramming~30 mins

Why actors prevent data races in Swift - See It in Action

Choose your learning style9 modes available
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 100
Add a function withdraw(amount:) inside the actor to subtract from balance
Create a constant account as an instance of BankAccount
Call withdraw(amount: 30) twice concurrently using Task
Print 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
1
Create the BankAccount actor with initial balance
Create an actor called BankAccount with a variable balance set to 100 inside it.
Swift
Need a hint?

Use the actor keyword and define var balance = 100 inside it.

2
Add a withdraw function to the actor
Inside the BankAccount actor, add a function called withdraw(amount: Int) that subtracts amount from balance.
Swift
Need a hint?

Define a function withdraw(amount: Int) that reduces balance by amount.

3
Create an instance and withdraw concurrently
Create a constant account as an instance of BankAccount. Then start two concurrent Tasks that each call await account.withdraw(amount: 30).
Swift
Need a hint?

Create let account = BankAccount() and use two Task blocks calling await account.withdraw(amount: 30).

4
Print the final balance after withdrawals
Add a Task that waits a moment and then prints await account.balance to show the final balance.
Swift
Need a hint?

Use Task.sleep to wait briefly, then print await account.balance.