0
0
Swiftprogramming~30 mins

Task groups for parallel execution in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Task groups for parallel execution
📖 Scenario: You are building a simple Swift program that fetches data from multiple sources at the same time. This helps your app work faster by doing tasks in parallel.
🎯 Goal: Learn how to use TaskGroup in Swift to run multiple tasks in parallel and collect their results.
📋 What You'll Learn
Create an array of URLs as strings
Create a variable to hold the number of URLs
Use a TaskGroup to fetch data from all URLs in parallel
Print the combined results after all tasks finish
💡 Why This Matters
🌍 Real World
Fetching data from multiple web services at the same time to improve app speed.
💼 Career
Understanding parallel execution with TaskGroup is important for building efficient Swift apps that handle multiple tasks concurrently.
Progress0 / 4 steps
1
Create the list of URLs
Create a constant array called urls with these exact string values: "https://site1.com", "https://site2.com", "https://site3.com".
Swift
Need a hint?

Use square brackets [] to create an array and separate strings with commas.

2
Create a count variable
Create a constant called count that stores the number of elements in the urls array using urls.count.
Swift
Need a hint?

Use urls.count to get the number of items in the array.

3
Use TaskGroup to fetch data in parallel
Inside an asynchronous function called fetchAllData(), use await withTaskGroup(of: String?.self) to create a task group named group. For each url in urls, add a task to group that returns a string like "Data from \(url)". Collect all results into an array called results.
Swift
Need a hint?

Use withTaskGroup to run tasks in parallel and collect their results in an array.

4
Print the combined results
Inside the fetchAllData() function, after collecting the results, print the results array using print(results). Then, call fetchAllData() from Task to run it asynchronously.
Swift
Need a hint?

Use print(results) to show the array. Use Task { await fetchAllData() } to run the async function.