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])
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?