Complete the code to start an asynchronous task using Swift's structured concurrency.
Task {
await [1]()
}The Task initializer creates a new asynchronous task. Inside it, you call await fetchData() to run the async function.
Complete the code to define an async function that returns a string after a delay.
func fetchData() async -> String {
try? await Task.sleep(nanoseconds: 1_000_000_000)
return [1]
}The function returns the string "Done". It must be a string literal with quotes.
Fix the error in the code by choosing the correct keyword to mark the function as asynchronous.
func loadData() [1] -> String { return "Loaded" }
The correct keyword to mark a function as asynchronous is async. It goes after the parameter list.
Fill both blanks to create a task group that runs two async functions concurrently and collects their results.
await withTaskGroup(of: String.self) { group in
group.[1] {
await fetchData1()
}
group.[2] {
await fetchData2()
}
}The method to add a new task to the group is addTask. Both blanks need this method to add tasks.
Fill all three blanks to create a dictionary that maps task results to their lengths, filtering only results longer than 3 characters.
let results = ["apple", "bat", "carrot"] let lengths = results.reduce(into: [String: Int]()) { lengths, [1] in if [2] > 3 { lengths[[3]] = [2] } }
The reduce(into:) uses word as key, word.count as value, and iterates with word over results.