How do I create and use Task and TaskGroup?

In Swift, you can utilize `Task` and `TaskGroup` for managing concurrent operations. `Task` allows you to create and run asynchronous tasks, while `TaskGroup` enables you to manage a group of tasks, waiting for all of them to complete. This is particularly useful when you need to perform multiple tasks concurrently and aggregate results from them.

Here’s an example of creating and using `Task` and `TaskGroup` in Swift:

import Foundation // Define a function that simulates a network call func fetchData(for id: Int) async -> String { // Simulating a network delay await Task.sleep(1_000_000_000) // 1 second return "Data for ID: \(id)" } // Using TaskGroup to manage concurrent fetching of data func fetchMultipleData(ids: [Int]) async { await withTaskGroup(of: String.self) { group in for id in ids { group.addTask { await fetchData(for: id) } } // Collecting results for await result in group { print(result) } } } // Calling the async function @main struct MyApp { static func main() async { await fetchMultipleData(ids: [1, 2, 3, 4, 5]) } }

Task TaskGroup Swift async concurrent programming