Consider this Swift code using an actor. What will be printed when printCounter() is called?
actor Counter {
var value = 0
func increment() {
value += 1
}
func printCounter() {
print("Counter value: \(value)")
}
}
let counter = Counter()
Task {
await counter.increment()
await counter.printCounter()
}Remember that actor methods must be called with await outside the actor.
The increment() method increases value by 1. Both methods are called with await inside a Task, so the actor isolation rules are respected. The printed value is 1.
Choose the statement that correctly explains actor isolation.
Think about how actors protect their data from concurrent access.
Actors isolate their mutable state so that only one task can access it at a time, preventing data races. This is done using asynchronous calls and await.
Examine this code snippet. What error will the compiler report?
actor BankAccount {
var balance = 1000
func deposit(amount: Int) {
balance += amount
}
}
let account = BankAccount()
account.deposit(amount: 500)Think about how actor methods must be called from outside the actor.
The method deposit is actor-isolated and must be called with await from outside the actor. Calling it synchronously causes a compiler error.
Choose the correct Swift code that declares an actor with a mutable property count initialized to 0.
Remember that mutable properties inside actors are declared with var.
Option D correctly declares a mutable property count initialized to 0. Option D uses let which is immutable. Option D declares a static property, which is shared and not isolated. Option D is valid syntax but unnecessarily verbose compared to A.
Given this Swift code, how many concurrent executions of increment() can happen inside the actor?
actor Counter {
var value = 0
func increment() {
value += 1
}
}
let counter = Counter()
Task {
await withTaskGroup(of: Void.self) { group in
for _ in 1...5 {
group.addTask {
await counter.increment()
}
}
}
}Think about how actor isolation serializes access to its mutable state.
Actors serialize access to their isolated state, so even though 5 tasks call increment() concurrently, only one executes at a time inside the actor, preventing data races.