Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start a task group in Swift.
Swift
try await [1](of: Int.self) { group in // parallel tasks here }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'group' or 'taskGroup' which are not valid Swift concurrency methods.
Confusing 'withGroup' with the correct 'withTaskGroup'.
✗ Incorrect
The correct method to start a task group in Swift concurrency is 'withTaskGroup'.
2fill in blank
mediumComplete the code to add a child task inside a task group.
Swift
try await withTaskGroup(of: Int.self) { group in group.[1] { return 42 } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'async' which is a keyword, not a method here.
Using 'spawn' which is not a Swift concurrency method.
✗ Incorrect
The method to add a child task to a task group is 'addTask'.
3fill in blank
hardFix the error in the code to await results from all child tasks in the group.
Swift
try await withTaskGroup(of: Int.self) { group in group.addTask { return 10 } var sum = 0 for await result in group.[1] { let value = try result.get() sum += value } return sum }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'values' which is not a property of TaskGroup.
Using 'await' as a property which is a keyword.
✗ Incorrect
The correct property to iterate over all child task results is 'results'.
4fill in blank
hardFill both blanks to create a task group that returns the first completed child task result.
Swift
try await withTaskGroup(of: Int.self) { group in group.[1] { return 5 } group.[2] { return 10 } for await result in group.results { return try result.get() } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different methods for adding tasks.
Using 'spawn' or 'async' which are invalid here.
✗ Incorrect
Both child tasks are added using 'addTask' method to the task group.
5fill in blank
hardFill all three blanks to create a task group that sums only even results from child tasks.
Swift
try await withTaskGroup(of: Int.self) { group in group.[1] { return 3 } group.[2] { return 4 } var total = 0 for await result in group.[3] { let number = try result.get() if number % 2 == 0 { total += number } } return total }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add' instead of 'addTask' to add child tasks.
Using 'values' instead of 'results' to iterate results.
✗ Incorrect
Child tasks are added with 'addTask' and results are iterated using 'results'.