📖 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
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
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
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
Hint
Use print("Balance is \(await myAccount.balance)") to show the balance.
Practice
(1/5)
1. What is the main purpose of actor isolation in Swift concurrency?
easy
A. To disable concurrency features in Swift
B. To ensure only one task accesses actor data at a time
C. To make actor methods run faster without waiting
D. To allow multiple tasks to modify actor data simultaneously
Solution
Step 1: Understand actor isolation concept
Actor isolation means only one task can access the actor's data at a time to avoid conflicts.
Step 2: Compare options with this concept
Only To ensure only one task accesses actor data at a time correctly describes this purpose; others contradict the idea of isolation.
Final Answer:
To ensure only one task accesses actor data at a time -> Option B
Quick Check:
Actor isolation = single task access [OK]
Hint: Actor isolation means single task access only [OK]
Common Mistakes:
Thinking actors allow simultaneous data changes
Confusing isolation with performance boost
Believing actor isolation disables concurrency
2. Which of the following is the correct way to call an actor's method from outside the actor in Swift?
easy
A. await actorInstance.method()
B. actorInstance.method()
C. async actorInstance.method()
D. actorInstance.method.await()
Solution
Step 1: Recall syntax for calling actor methods
Calling an actor's method from outside requires using await to handle asynchronous access.
Step 2: Match options with correct syntax
Only await actorInstance.method() uses await correctly before the method call.
Final Answer:
await actorInstance.method() -> Option A
Quick Check:
Use await before actor method call [OK]
Hint: Always use await before calling actor methods externally [OK]
Common Mistakes:
Omitting await causing compile errors
Using async keyword incorrectly
Placing await after method call
3. Consider this Swift code snippet:
actor Counter {
var value = 0
func increment() {
value += 1
}
}
let counter = Counter()
Task {
await counter.increment()
print(await counter.value)
}
What will be printed when this code runs?
medium
A. 1
B. 0
C. Compilation error
D. Runtime crash
Solution
Step 1: Understand actor method and property access
The method increment() increases value by 1. Accessing value outside requires await.
Step 2: Trace code execution
The task calls await counter.increment() which adds 1, then prints await counter.value, so output is 1.
Final Answer:
1 -> Option A
Quick Check:
Increment then print value = 1 [OK]
Hint: Increment then await value to print updated number [OK]
Common Mistakes:
Forgetting await on property access
Assuming value remains 0 without increment
Expecting compile or runtime errors
4. Identify the error in this Swift actor usage:
actor BankAccount {
var balance = 1000
func withdraw(amount: Int) {
balance -= amount
}
}
let account = BankAccount()
account.withdraw(amount: 100)
print(account.balance)
medium
A. Cannot print actor properties
B. balance should be a constant
C. withdraw method must be static
D. Missing await when calling actor method
Solution
Step 1: Check actor method call rules
Calling an actor's method from outside must use await because it is asynchronous.
Step 2: Identify missing await
The code calls account.withdraw(amount: 100) without await, causing a compile error.
Final Answer:
Missing await when calling actor method -> Option D
Quick Check:
Actor method calls need await [OK]
Hint: Always await actor method calls outside actor [OK]
Common Mistakes:
Calling actor methods without await
Thinking actor properties can't be printed
Believing methods must be static
5. You want to safely update a shared counter from multiple tasks using an actor. Which approach correctly ensures safe concurrent increments?
hard
A. Use a global variable and increment without synchronization
B. Use a struct with a mutating method called from multiple tasks
C. Define an actor with a method to increment the counter and call it with await
D. Use a class with a property and increment it directly from tasks
Shared data must be accessed safely to avoid race conditions; actors provide this by isolating data.
Step 2: Evaluate each option for safety
Define an actor with a method to increment the counter and call it with await uses an actor with an increment method called with await, ensuring safe access. Others lack synchronization.
Final Answer:
Define an actor with a method to increment the counter and call it with await -> Option C
Quick Check:
Actor method with await ensures safe concurrent updates [OK]
Hint: Use actor methods with await for safe shared data updates [OK]
Common Mistakes:
Ignoring synchronization with global variables
Using structs or classes without concurrency control
Assuming direct property access is safe
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.