0
0
Swiftprogramming~20 mins

Cancellation handling in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Cancellation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A
Step 1 completed
Step 2 completed
Task finished
B
Step 1 completed
Step 2 completed
Step 3 completed
C
Step 1 completed
Step 2 completed
Step 3 completed
Task finished
D
Step 1 completed
Step 2 completed
Attempts:
2 left
💡 Hint
Cancellation is checked before each step and the task is cancelled after 1.2 seconds.
🧠 Conceptual
intermediate
1: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?
AThe Task continues running until it finishes or checks for cancellation explicitly.
BThe Task immediately stops execution and throws a cancellation error.
CThe Task restarts automatically from the beginning.
DThe Task pauses and waits for manual resume.
Attempts:
2 left
💡 Hint
Cancellation requires explicit checks in Swift concurrency.
🔧 Debug
advanced
2: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
ABecause Task.sleep ignores cancellation requests.
BBecause the function does not call Task.checkCancellation() to detect cancellation.
CBecause the Task.cancel() call is ignored in async functions.
DBecause the loop range is fixed and cannot be interrupted.
Attempts:
2 left
💡 Hint
Cancellation requires explicit checks in Swift async code.
📝 Syntax
advanced
2: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")
    }
}
AUse try await task.value inside do-catch to catch cancellation error and print message.
BUse task.cancel() and ignore task.value completely.
CUse task.cancel() and then immediately call task.value without await or try.
DUse try? await task.value without catch block to ignore cancellation error.
Attempts:
2 left
💡 Hint
Cancellation throws an error that must be caught.
🚀 Application
expert
2: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
A5 times
B3 times
C4 times
D6 times
Attempts:
2 left
💡 Hint
Each loop iteration takes about 0.3 seconds, cancellation happens after 1 second.