Challenge - 5 Problems
Swift Cancellation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift async cancellation check?
Consider this Swift async function that checks for cancellation inside a loop. What will be printed when the task is cancelled during execution?
Swift
func performTask() async { for i in 1...5 { try Task.checkCancellation() print("Step \(i) completed") try await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds } print("Task finished") } let task = Task { await performTask() } Task { try await Task.sleep(nanoseconds: 1_200_000_000) // 1.2 seconds task.cancel() } // Wait for task to finish try await task.value
Attempts:
2 left
💡 Hint
Cancellation is checked before each step and the task is cancelled after 1.2 seconds.
✗ Incorrect
The task runs steps with 0.5 seconds delay each. After 1.2 seconds, cancellation is requested. The cancellation check stops the loop after step 2 completes, so only steps 1 and 2 print. The task does not reach step 3 or finish message.
🧠 Conceptual
intermediate1:30remaining
What happens when a Swift Task is cancelled but cancellation is not checked?
In Swift concurrency, if a Task is cancelled but the code inside does not check for cancellation, what is the behavior?
Attempts:
2 left
💡 Hint
Cancellation requires explicit checks in Swift concurrency.
✗ Incorrect
In Swift, cancelling a Task sets its cancellation flag, but the Task code must check for cancellation using Task.checkCancellation() or similar. Without checks, the Task runs normally.
🔧 Debug
advanced2:00remaining
Why does this Swift async function not stop when cancelled?
Given this Swift async function, why does it not stop when the Task is cancelled?
func fetchData() async {
for i in 1...3 {
print("Fetching chunk \(i)")
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
print("Fetch complete")
}
let task = Task {
await fetchData()
}
Task {
try? await Task.sleep(nanoseconds: 1_500_000_000)
task.cancel()
}
try? await task.value
Attempts:
2 left
💡 Hint
Cancellation requires explicit checks in Swift async code.
✗ Incorrect
The function never checks for cancellation explicitly. Task.sleep can throw if cancelled, but try? ignores errors, so cancellation is not detected and the loop continues.
📝 Syntax
advanced2:00remaining
Which option correctly cancels a Swift Task and handles cancellation error?
Which code snippet correctly cancels a Swift Task and handles the cancellation error properly?
Swift
func longRunningTask() async throws { for i in 1...5 { try Task.checkCancellation() print("Processing \(i)") try await Task.sleep(nanoseconds: 500_000_000) } } let task = Task { try await longRunningTask() } Task { try await Task.sleep(nanoseconds: 1_200_000_000) task.cancel() do { try await task.value } catch { print("Task was cancelled") } }
Attempts:
2 left
💡 Hint
Cancellation throws an error that must be caught.
✗ Incorrect
Cancellation throws a CancellationError. Using try await task.value inside a do-catch block allows catching this error and handling it gracefully.
🚀 Application
expert2:30remaining
How many times will the print statement execute before cancellation stops the task?
Analyze this Swift async function that checks cancellation and sleeps. How many times will "Working..." print before the task is cancelled?
func work() async throws {
var count = 0
while true {
try Task.checkCancellation()
print("Working... \(count)")
count += 1
try await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
}
}
let task = Task {
try await work()
}
Task {
try await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
task.cancel()
}
try? await task.value
Attempts:
2 left
💡 Hint
Each loop iteration takes about 0.3 seconds, cancellation happens after 1 second.
✗ Incorrect
Each iteration prints then sleeps 0.3 seconds. After 1 second, cancellation is requested. The task completes 3 full iterations and starts the 4th before cancellation is detected, so 4 prints occur.