0
0
iOS Swiftmobile~20 mins

Task and TaskGroup in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
TaskGroup Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ui_behavior
intermediate
2:00remaining
Understanding TaskGroup concurrency behavior
Consider this Swift code using TaskGroup. What will be printed first?
iOS Swift
func testTaskGroup() async {
  await withTaskGroup(of: String.self) { group in
    group.addTask { "First" }
    group.addTask { "Second" }
    for await result in group {
      print(result)
      break
    }
  }
  print("Done")
}

Task {
  await testTaskGroup()
}
ADone\nSecond
BSecond\nDone
CDone\nFirst
DFirst\nDone
Attempts:
2 left
💡 Hint
The first completed task result is printed before breaking the loop.
lifecycle
intermediate
2:00remaining
Task cancellation inside TaskGroup
What happens if a task inside a TaskGroup calls Task.cancel() on itself?
iOS Swift
func cancelInsideGroup() async {
  await withTaskGroup(of: Void.self) { group in
    group.addTask {
      Task.cancel()
      print("Cancelled")
    }
    group.addTask {
      print("Running")
    }
  }
}

Task {
  await cancelInsideGroup()
}
APrints "Cancelled" and "Running"
BPrints only "Running"
CPrints only "Cancelled"
DNo output, tasks are cancelled immediately
Attempts:
2 left
💡 Hint
Cancellation does not stop the current task immediately.
📝 Syntax
advanced
2:00remaining
Correct syntax for adding tasks in TaskGroup
Which option correctly adds a task returning an Int in a TaskGroup?
iOS Swift
func addTaskExample() async {
  await withTaskGroup(of: Int.self) { group in
    // Add a task here
  }
}
Agroup.addTask { 42 }
Bgroup.addTask { return 42 }
Cgroup.addTask { await 42 }
Dgroup.addTask { async { 42 } }
Attempts:
2 left
💡 Hint
The closure can return the value directly without return keyword.
🔧 Debug
advanced
2:00remaining
Why does this TaskGroup code deadlock?
Given this code, why does it deadlock?
iOS Swift
func deadlockExample() async {
  await withTaskGroup(of: Void.self) { group in
    group.addTask {
      await deadlockExample() // recursive call
    }
  }
}

Task {
  await deadlockExample()
}
ABecause the task is not awaited properly
BBecause the recursive call waits for the group to finish, causing a cycle
CBecause TaskGroup does not support recursion
DBecause the group is empty and never completes
Attempts:
2 left
💡 Hint
Think about waiting inside the group for itself to finish.
🧠 Conceptual
expert
2:00remaining
TaskGroup result ordering guarantee
Which statement about the order of results from withTaskGroup is true?
AResults are returned in the order tasks were added
BResults are returned in random order each run
CResults are returned in the order tasks complete
DResults are returned sorted by their value
Attempts:
2 left
💡 Hint
Think about concurrency and task completion timing.