Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a simple asynchronous task that prints a message.
iOS Swift
Task {
print([1])
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the string.
Trying to print without a string argument.
✗ Incorrect
The print function requires a string argument in quotes. Option D correctly provides a string literal.
2fill in blank
mediumComplete the code to create a TaskGroup that runs two tasks concurrently.
iOS Swift
Task {
await withTaskGroup(of: Void.self) { group in
group.addTask {
print("Task 1")
}
group.addTask {
print([1])
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Missing quotes around the string.
Trying to call print inside print.
✗ Incorrect
Inside the print function, the argument must be a string literal with quotes. Option C is correct.
3fill in blank
hardFix the error in the TaskGroup code by completing the blank with the correct keyword to wait for all tasks.
iOS Swift
Task {
[1] withTaskGroup(of: Int.self) { group in
group.addTask { 1 }
group.addTask { 2 }
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'async' instead of 'await'.
Omitting the keyword entirely.
✗ Incorrect
The 'await' keyword is needed to wait for the TaskGroup to complete its tasks asynchronously.
4fill in blank
hardFill both blanks to create a TaskGroup that returns the sum of two asynchronous tasks.
iOS Swift
let sum = await withTaskGroup(of: Int.self) { group in
group.addTask { 5 }
group.addTask { 10 }
var total = 0
for await [1] in group {
total [2] [1]
}
return total
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' instead of '+='.
Using a loop variable name not matching the code.
✗ Incorrect
The loop variable should be 'value' to hold each task result, and '+=' adds it to total.
5fill in blank
hardFill all three blanks to create a TaskGroup that returns the maximum value from three asynchronous tasks.
iOS Swift
let maxValue = await withTaskGroup(of: Int.self) { group in
group.addTask { 3 }
group.addTask { 7 }
group.addTask { 5 }
var maxVal = Int.min
for await [1] in group {
if [1] [2] maxVal {
maxVal = [1]
}
}
return maxVal
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the comparison.
Using inconsistent variable names.
✗ Incorrect
The loop variable is 'result'. We compare if result > maxVal, then update maxVal with result.