0
0
Swiftprogramming~10 mins

Task groups for parallel execution 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 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'
Agroup
BwithGroup
CwithTaskGroup
DtaskGroup
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'group' or 'taskGroup' which are not valid Swift concurrency methods.
Confusing 'withGroup' with the correct 'withTaskGroup'.
2fill in blank
medium

Complete 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'
Aadd
BaddTask
Cspawn
Dasync
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.
3fill in blank
hard

Fix 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'
Aresults
Bvalues
Call
Dawait
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'values' which is not a property of TaskGroup.
Using 'await' as a property which is a keyword.
4fill in blank
hard

Fill 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'
Aadd
Bspawn
CaddTask
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Using different methods for adding tasks.
Using 'spawn' or 'async' which are invalid here.
5fill in blank
hard

Fill 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'
AaddTask
Badd
Cresults
Dvalues
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add' instead of 'addTask' to add child tasks.
Using 'values' instead of 'results' to iterate results.