Bird
Raised Fist0
iOS Swiftmobile~20 mins

Task and TaskGroup in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Task Manager
This screen shows a list of tasks grouped by categories. Each group has a header and tasks listed below. Users can see task names and their status (done or not).
Target UI
-------------------------
| Task Manager          |
-------------------------
| Work                 |
|  - Email client [ ]   |
|  - Prepare report [x] |
|-----------------------|
| Home                 |
|  - Clean kitchen [ ]  |
|  - Fix sink [ ]       |
-------------------------
Display tasks grouped by their category name as section headers
Each task shows its name and a checkbox indicating if it is done
Use Swift concurrency Task and TaskGroup to simulate loading tasks asynchronously
Show a loading indicator while tasks load
After loading, display the grouped tasks in a List
Starter Code
iOS Swift
import SwiftUI

struct TaskItem: Identifiable {
  let id = UUID()
  let name: String
  let done: Bool
}

struct TaskGroupData: Identifiable {
  let id = UUID()
  let category: String
  let tasks: [TaskItem]
}

struct TaskManagerView: View {
  @State private var taskGroups: [TaskGroupData] = []
  @State private var isLoading = true

  var body: some View {
    NavigationView {
      Group {
        if isLoading {
          ProgressView("Loading tasks...")
        } else {
          List {
            // TODO: Show grouped tasks here
          }
          .listStyle(GroupedListStyle())
        }
      }
      .navigationTitle("Task Manager")
      .task {
        // TODO: Load tasks asynchronously using TaskGroup
      }
    }
  }
}

struct TaskManagerView_Previews: PreviewProvider {
  static var previews: some View {
    TaskManagerView()
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import SwiftUI

struct TaskItem: Identifiable {
  let id = UUID()
  let name: String
  let done: Bool
}

struct TaskGroupData: Identifiable {
  let id = UUID()
  let category: String
  let tasks: [TaskItem]
}

struct TaskManagerView: View {
  @State private var taskGroups: [TaskGroupData] = []
  @State private var isLoading = true

  var body: some View {
    NavigationView {
      Group {
        if isLoading {
          ProgressView("Loading tasks...")
            .progressViewStyle(CircularProgressViewStyle())
        } else {
          List {
            ForEach(taskGroups) { group in
              Section(header: Text(group.category)) {
                ForEach(group.tasks) { task in
                  HStack {
                    Text(task.name)
                    Spacer()
                    Image(systemName: task.done ? "checkmark.square" : "square")
                      .foregroundColor(task.done ? .green : .secondary)
                      .accessibilityLabel(task.done ? "Done" : "Not done")
                  }
                  .padding(.vertical, 4)
                }
              }
            }
          }
          .listStyle(GroupedListStyle())
        }
      }
      .navigationTitle("Task Manager")
      .task {
        await loadTasks()
      }
    }
  }

  func loadTasks() async {
    isLoading = true
    var loadedGroups: [TaskGroupData] = []

    await withTaskGroup(of: TaskGroupData?.self) { group in
      let categories = ["Work", "Home"]

      for category in categories {
        group.addTask {
          // Simulate network delay
          try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second

          switch category {
          case "Work":
            let tasks = [
              TaskItem(name: "Email client", done: false),
              TaskItem(name: "Prepare report", done: true)
            ]
            return TaskGroupData(category: category, tasks: tasks)
          case "Home":
            let tasks = [
              TaskItem(name: "Clean kitchen", done: false),
              TaskItem(name: "Fix sink", done: false)
            ]
            return TaskGroupData(category: category, tasks: tasks)
          default:
            return nil
          }
        }
      }

      for await result in group {
        if let groupData = result {
          loadedGroups.append(groupData)
        }
      }
    }

    // Sort groups by category name
    taskGroups = loadedGroups.sorted { $0.category < $1.category }
    isLoading = false
  }
}

struct TaskManagerView_Previews: PreviewProvider {
  static var previews: some View {
    TaskManagerView()
  }
}

This solution uses Swift concurrency's withTaskGroup to load task groups asynchronously. Each category is loaded in its own child task with a simulated 1-second delay to mimic network loading.

After all tasks complete, the results are collected and sorted alphabetically by category. The UI shows a loading spinner while loading, then displays the tasks grouped by category in a List with sections.

Each task row shows the task name and a checkbox icon that is green if done, or gray if not. Accessibility labels describe the checkbox state for screen readers.

This approach teaches how to use TaskGroup to run multiple async tasks concurrently and update UI state when all finish.

Final Result
Completed Screen
-------------------------
| Task Manager          |
-------------------------
| Work                 |
|  - Email client [ ]   |
|  - Prepare report [x] |
|-----------------------|
| Home                 |
|  - Clean kitchen [ ]  |
|  - Fix sink [ ]       |
-------------------------
When the screen appears, a circular loading spinner with text 'Loading tasks...' shows for about 1 second.
Then the list of tasks grouped by 'Work' and 'Home' appears.
Each task shows a checkbox: checked for done tasks, empty for not done.
User can scroll the list if needed.
Stretch Goal
Add the ability to tap a task to toggle its done status in the UI.
💡 Hint
Use @State to track tasks and update the done property on tap. Use a Button or onTapGesture on each task row.

Practice

(1/5)
1. What is the main purpose of a Task in Swift concurrency?
easy
A. To run a single background job asynchronously
B. To group multiple tasks and run them together
C. To update the UI on the main thread
D. To pause the app execution

Solution

  1. Step 1: Understand what Task does

    A Task is designed to run one asynchronous job in the background.
  2. Step 2: Differentiate from TaskGroup

    TaskGroup runs many jobs together, not a single job.
  3. Final Answer:

    To run a single background job asynchronously -> Option A
  4. Quick Check:

    Task = single background job [OK]
Hint: Task runs one job; TaskGroup runs many [OK]
Common Mistakes:
  • Confusing Task with TaskGroup
  • Thinking Task updates UI directly
  • Assuming Task pauses app execution
2. Which of the following is the correct syntax to create a Task that prints "Hello" asynchronously?
easy
A. async Task { print("Hello") }
B. TaskGroup { print("Hello") }
C. Task.run { print("Hello") }
D. Task { print("Hello") }

Solution

  1. Step 1: Recall correct Task syntax

    The correct way to create a Task is using Task { ... } with a closure.
  2. Step 2: Check other options for errors

    TaskGroup is not used like this; async Task and Task.run are invalid syntax.
  3. Final Answer:

    Task { print("Hello") } -> Option D
  4. Quick Check:

    Correct Task syntax = Task { print("Hello") } [OK]
Hint: Use Task { } with closure for async code [OK]
Common Mistakes:
  • Using TaskGroup instead of Task
  • Adding 'async' keyword before Task
  • Trying to call Task.run which doesn't exist
3. What will be printed by this Swift code using TaskGroup?
func fetchData() async {
  await withTaskGroup(of: String.self) { group in
    group.addTask { "A" }
    group.addTask { "B" }
    for await result in group {
      print(result)
    }
  }
}
fetchData()
medium
A. Either A then B or B then A (order not guaranteed)
B. B then A in order
C. A then B in order
D. No output because of syntax error

Solution

  1. Step 1: Understand TaskGroup concurrency

    TaskGroup runs tasks concurrently and collects results as they finish, order is not guaranteed.
  2. Step 2: Analyze the code output

    Since tasks return "A" and "B" concurrently, the print order can be either "A" then "B" or "B" then "A".
  3. Final Answer:

    Either A then B or B then A (order not guaranteed) -> Option A
  4. Quick Check:

    TaskGroup results order is unpredictable [OK]
Hint: TaskGroup runs tasks concurrently; output order varies [OK]
Common Mistakes:
  • Assuming TaskGroup results are always ordered
  • Thinking tasks run sequentially
  • Believing syntax error prevents output
4. Identify the error in this Swift code using TaskGroup:
await withTaskGroup(of: Int.self) { group in
  group.addTask { 1 }
  group.addTask { 2 }
  for result in group {
    print(result)
  }
}
medium
A. Incorrect type in 'withTaskGroup' declaration
B. Using 'for' instead of 'for await' to iterate the group
C. Missing 'await' before 'for' loop
D. Cannot add tasks inside 'withTaskGroup'

Solution

  1. Step 1: Check iteration over TaskGroup

    Iteration over a TaskGroup is asynchronous, so it requires for await.
  2. Step 2: Identify the error in the code

    The code uses for result in group without await, causing a compile error.
  3. Final Answer:

    Using 'for' instead of 'for await' to iterate the group -> Option B
  4. Quick Check:

    Async iteration needs 'for await' [OK]
Hint: Use 'for await' to loop over TaskGroup results [OK]
Common Mistakes:
  • Forgetting 'await' in asynchronous loops
  • Confusing TaskGroup type declaration
  • Thinking tasks can't be added inside withTaskGroup
5. You want to fetch user data from three different servers concurrently and combine the results. Which Swift concurrency pattern using TaskGroup is best to achieve this?
hard
A. Create three separate Task instances and wait for each sequentially
B. Run three synchronous functions one after another on the main thread
C. Use a TaskGroup to add three tasks fetching data, then collect all results asynchronously
D. Use a single Task that fetches data from all servers sequentially

Solution

  1. Step 1: Understand concurrency needs

    Fetching from three servers concurrently requires running tasks in parallel to save time.
  2. Step 2: Choose the best Swift concurrency pattern

    TaskGroup allows adding multiple tasks and collecting results asynchronously, perfect for this use case.
  3. Final Answer:

    Use a TaskGroup to add three tasks fetching data, then collect all results asynchronously -> Option C
  4. Quick Check:

    TaskGroup = concurrent multiple tasks [OK]
Hint: Use TaskGroup for multiple concurrent tasks and results [OK]
Common Mistakes:
  • Running tasks sequentially losing concurrency benefits
  • Using synchronous calls blocking main thread
  • Using single Task for sequential fetches
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard