0
0
Swiftprogramming~10 mins

Cancellation handling in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a task has been cancelled.

Swift
if Task.isCancelled [1] {
    print("Task was cancelled")
}
Drag options to blanks, or click blank then click option'
Ais
B== false
C!=
D== true
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' false instead of '== true'
Using 'is' keyword incorrectly
Omitting the comparison operator
2fill in blank
medium

Complete the code to throw a cancellation error inside an async task.

Swift
func fetchData() async throws {
    guard !Task.[1] else {
        throw CancellationError()
    }
    // continue fetching data
}
Drag options to blanks, or click blank then click option'
AisCancelled
Bcancelled
Ccancel
DisCanceling
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect property names like 'cancelled' or 'cancel'
Using 'isCanceling' which does not exist
3fill in blank
hard

Fix the error in the code to properly handle cancellation inside a Task.

Swift
Task {
    try await someAsyncFunction()
    if [1] {
        print("Cancelled")
    }
}
Drag options to blanks, or click blank then click option'
Aself.cancelled
BTask.cancelled
CTask.isCancelled
Dself.isCancelled
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance properties instead of the static property
Using incorrect property names
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that includes only non-cancelled tasks.

Swift
let activeTasks = [task: status for (task, status) in allTasks if task.[1] == false && !Task.[2]]
Drag options to blanks, or click blank then click option'
AisCancelled
Bcancelled
Dcanceling
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'cancelled' or 'canceling' which are not valid properties
Mixing instance and static properties incorrectly
5fill in blank
hard

Fill all three blanks to create a dictionary of task names and statuses for tasks that are not cancelled.

Swift
let filteredTasks = [[1]: [2] for ([3], status) in tasks if ![3].isCancelled]
Drag options to blanks, or click blank then click option'
Atask.name
Bstatus
Ctask
Dtasks
Attempts:
3 left
💡 Hint
Common Mistakes
Using the whole task as key instead of task.name
Using wrong variable names in the loop