Challenge - 5 Problems
Swift Actor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of actor method call
What is the output of this Swift code using an actor?
Swift
actor Counter {
var value = 0
func increment() async -> Int {
value += 1
return value
}
}
let counter = Counter()
Task {
let result = await counter.increment()
print(result)
}Attempts:
2 left
💡 Hint
Remember that actor methods are asynchronous and state changes inside actors are safe.
✗ Incorrect
The actor Counter starts with value 0. Calling increment() adds 1 and returns the new value, which is 1.
📝 Syntax
intermediate2:00remaining
Identify the correct actor declaration
Which of the following is the correct syntax to declare an actor named Logger in Swift?
Attempts:
2 left
💡 Hint
Actors are declared like classes but with the keyword 'actor' and no parentheses.
✗ Incorrect
Option A correctly declares an actor named Logger with a method log. Option A wrongly uses 'actor func' inside a class. Option A uses parentheses after actor name which is invalid. Option A wrongly uses 'actor func' inside actor.
🔧 Debug
advanced2:00remaining
Why does this actor code cause a compile error?
Consider this Swift code:
actor BankAccount {
var balance: Int = 0
func deposit(amount: Int) {
balance += amount
}
}
let account = BankAccount()
account.deposit(amount: 100)
Why does this code cause a compile error?
Swift
actor BankAccount {
var balance: Int = 0
func deposit(amount: Int) async {
balance += amount
}
}
let account = BankAccount()
Task {
await account.deposit(amount: 100)
}Attempts:
2 left
💡 Hint
Think about how actor methods are called from outside the actor.
✗ Incorrect
Actor methods are isolated and asynchronous by default. Calling deposit requires 'await' keyword to handle concurrency.
🧠 Conceptual
advanced2:00remaining
Actor isolation and data race prevention
Which statement best describes how actors prevent data races in Swift?
Attempts:
2 left
💡 Hint
Think about how actors handle concurrent access to their properties.
✗ Incorrect
Actors ensure only one task can access their mutable state at a time, preventing data races without explicit locks.
❓ Predict Output
expert2:00remaining
Output of concurrent actor calls
What is the output of this Swift code using an actor with concurrent tasks?
Swift
actor Counter {
var value = 0
func increment() async -> Int {
value += 1
return value
}
}
let counter = Counter()
Task {
async let a = counter.increment()
async let b = counter.increment()
let results = await [a, b]
print(results.sorted())
}Attempts:
2 left
💡 Hint
Actors serialize access, so increments happen one after another.
✗ Incorrect
The two increments happen sequentially inside the actor, so values returned are 1 and 2 in some order.