0
0
Swiftprogramming~30 mins

Actor isolation concept in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Actor Isolation in Swift
📖 Scenario: Imagine you are building a simple app that keeps track of a bank account balance. To keep the balance safe from being changed by multiple parts of the app at the same time, you use Swift's actor to protect the balance.
🎯 Goal: You will create an Account actor that holds a balance. Then, you will add a method to deposit money safely. Finally, you will print the updated balance.
📋 What You'll Learn
Create an actor named Account with a balance property of type Int.
Add a method deposit(amount: Int) inside the actor to add money to the balance.
Create an instance of Account named myAccount.
Call the deposit(amount: 100) method on myAccount.
Print the updated balance using await to access the actor's property.
💡 Why This Matters
🌍 Real World
Actors help keep data safe in apps where many parts run at the same time, like banking apps or games.
💼 Career
Understanding actor isolation is important for writing safe, modern Swift code that avoids bugs from data conflicts.
Progress0 / 4 steps
1
Create the Account actor with a balance
Create an actor named Account with a property balance set to 0.
Swift
Need a hint?

Use the actor keyword to define the actor and add a variable balance initialized to 0.

2
Add a deposit method to the Account actor
Inside the Account actor, add a func deposit(amount: Int) that adds amount to balance.
Swift
Need a hint?

Define a function deposit that takes amount and adds it to balance.

3
Create an instance of Account and deposit money
Create a constant myAccount as an instance of Account. Then call myAccount.deposit(amount: 100) using await.
Swift
Need a hint?

Create myAccount with Account() and call deposit with await.

4
Print the updated balance from the actor
Print the updated balance of myAccount using await and print.
Swift
Need a hint?

Use print("Balance is \(await myAccount.balance)") to show the balance.