Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start a new asynchronous task using Swift's structured concurrency.
Swift
Task.[1] { print("Hello from a new task!") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Task.start or Task.run which do not exist.
Confusing Task.detached with Task.init.
✗ Incorrect
In Swift's structured concurrency, you create a new detached task using Task.detached { ... }.
2fill in blank
mediumComplete the code to await the result of an asynchronous function call.
Swift
func fetchData() async -> String {
return "Data"
}
func process() async {
let result = [1] fetchData()
print(result)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use 'await' before calling an async function.
Using 'async' instead of 'await' in the function body.
✗ Incorrect
The 'await' keyword is used to wait for an asynchronous function to complete and return its result.
3fill in blank
hardFix the error in the code by completing the blank to correctly create a child task within a task group.
Swift
func downloadAll() async {
await withTaskGroup(of: String.self) { group in
group.[1] {
return "File 1"
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like startTask or createTask.
Trying to use Task.detached inside the group.
✗ Incorrect
In Swift's structured concurrency, you add child tasks to a task group using group.addTask { ... }.
4fill in blank
hardFill both blanks to create a task group that collects results from multiple child tasks.
Swift
func fetchAll() async {
let results = await withTaskGroup(of: String.self) { group in
group.[1] {
return "Data 1"
}
group.[2] {
return "Data 2"
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different methods for each task.
Using methods that do not exist on the group.
✗ Incorrect
You add multiple child tasks to a task group using group.addTask { ... } for each task.
5fill in blank
hardFill all three blanks to create a task group that adds tasks and processes their results.
Swift
func processFiles() async {
await withTaskGroup(of: String.self) { group in
group.[1] {
return "File A"
}
group.[2] {
return "File B"
}
for await result in group.[3] {
print(result)
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using startTask instead of addTask.
Trying to iterate over group.tasks instead of group.results.
✗ Incorrect
You add tasks with addTask and iterate over the group's results property to get completed task results.