0
0
Swiftprogramming~20 mins

Why actors prevent data races in Swift - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Actor Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Understanding actor isolation in Swift
What will be the output of this Swift code using an actor to protect shared data?
Swift
actor Counter {
    var value = 0
    func increment() async {
        value += 1
    }
    func getValue() async -> Int {
        return value
    }
}

let counter = Counter()
Task {
    await counter.increment()
    let val = await counter.getValue()
    print(val)
}
ARuntime error due to data race
B0
CCompilation error due to missing await
D1
Attempts:
2 left
💡 Hint
Remember that actors serialize access to their mutable state.
🧠 Conceptual
intermediate
1:30remaining
Why do actors prevent data races?
Which statement best explains why Swift actors prevent data races?
AActors serialize access to their mutable state, ensuring only one task can modify it at a time.
BActors allow multiple threads to write to the same variable simultaneously.
CActors disable concurrency to avoid any parallel execution.
DActors copy all data before modifying it, so no shared state exists.
Attempts:
2 left
💡 Hint
Think about how actors control access to their internal data.
🔧 Debug
advanced
2:30remaining
Identify the data race in this Swift code
What error or problem will occur when running this code without using an actor?
Swift
class Counter {
    var value = 0
    func increment() {
        value += 1
    }
}

let counter = Counter()
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
    counter.increment()
}
print(counter.value)
AThe printed value will always be 1000
BThe printed value may be less than 1000 due to a data race
CCompilation error because DispatchQueue.concurrentPerform is not allowed
DRuntime crash due to actor isolation violation
Attempts:
2 left
💡 Hint
Consider what happens when multiple threads modify the same variable without synchronization.
📝 Syntax
advanced
2:00remaining
Which code snippet correctly uses an actor to prevent data races?
Choose the code that correctly defines and uses an actor to safely increment a counter.
A
actor Counter {
    var value = 0
    func increment() async {
        value += 1
    }
}

let counter = Counter()
await counter.increment()
B
actor Counter {
    var value = 0
    func increment() {
        value += 1
    }
}

let counter = Counter()
counter.increment()
C
class Counter {
    var value = 0
    func increment() async {
        value += 1
    }
}

let counter = Counter()
await counter.increment()
D
actor Counter {
    var value = 0
    func increment() async {
        value += 1
    }
}

let counter = Counter()
counter.increment()
Attempts:
2 left
💡 Hint
Remember that actor methods that modify state are asynchronous and must be awaited.
🚀 Application
expert
3:00remaining
Predict the final value with concurrent actor calls
Given this Swift code, what is the final printed value of the counter after all tasks complete?
Swift
actor Counter {
    var value = 0
    func increment() async {
        let current = value
        try? await Task.sleep(nanoseconds: 1_000_000) // simulate delay
        value = current + 1
    }
    func getValue() async -> Int {
        return value
    }
}

let counter = Counter()

Task {
    await withTaskGroup(of: Void.self) { group in
        for _ in 1...10 {
            group.addTask {
                await counter.increment()
            }
        }
    }
    let finalValue = await counter.getValue()
    print(finalValue)
}
A0
B1
C10
DRuntime error due to data race
Attempts:
2 left
💡 Hint
Actors serialize access even if tasks run concurrently.