Bird
Raised Fist0
Swiftprogramming~20 mins

Structured concurrency model in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Concurrency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of async let with structured concurrency
What is the output of this Swift code using structured concurrency with async let?
Swift
func fetchNumber() async -> Int {
    return 10
}

func fetchDouble() async -> Int {
    return 20
}

func test() async {
    async let a = fetchNumber()
    async let b = fetchDouble()
    let sum = await a + await b
    print(sum)
}

Task {
    await test()
}
A30
B10
C20
DCompilation error
Attempts:
2 left
💡 Hint
Remember that async let runs tasks concurrently and you must await their results.
🧠 Conceptual
intermediate
1:30remaining
Understanding Task Groups in Swift concurrency
Which statement best describes the behavior of TaskGroup in Swift's structured concurrency?
ATaskGroup runs child tasks sequentially and returns after the first completes.
BTaskGroup runs child tasks concurrently but does not wait for any to finish.
CTaskGroup runs child tasks concurrently and waits for all to complete before continuing.
DTaskGroup runs child tasks sequentially and returns immediately.
Attempts:
2 left
💡 Hint
Think about how structured concurrency manages child tasks and their lifetimes.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in this structured concurrency code
What runtime error will this Swift code produce when executed?
Swift
func test() async {
    async let a = Task.sleep(nanoseconds: 1_000_000_000) // 1 second
    print("Before await")
    let _ = await a
    print("After await")
}

Task {
    await test()
}
ARuntime error: Task cancellation error
BNo error, prints 'Before await' then 'After await' after 1 second
CCompilation error due to incorrect Task.sleep usage
DDeadlock error because async let cannot be awaited
Attempts:
2 left
💡 Hint
Check how Task.sleep is used and awaited in async let.
❓ Predict Output
advanced
2:30remaining
Output of nested TaskGroup with cancellation
What will be printed by this Swift code using nested TaskGroups and cancellation?
Swift
func test() async {
    await withTaskGroup(of: Void.self) { group in
        group.addTask {
            print("Task 1 start")
            try? await Task.sleep(nanoseconds: 500_000_000)
            print("Task 1 end")
        }
        group.addTask {
            print("Task 2 start")
            Task.current.cancel()
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            print("Task 2 end")
        }
    }
}

Task {
    await test()
}
ANo output due to immediate cancellation
B
Task 1 start
Task 2 start
Task 2 end
Task 1 end
C
Task 2 start
Task 1 start
Task 2 end
D
Task 1 start
Task 2 start
Task 1 end
Attempts:
2 left
💡 Hint
Consider how cancellation affects running tasks and which prints happen before cancellation.
🧠 Conceptual
expert
1:30remaining
Effect of structured concurrency on resource cleanup
Which best describes how Swift's structured concurrency model helps with resource cleanup in asynchronous code?
AIt automatically cancels child tasks when the parent task finishes or throws an error, ensuring cleanup.
BIt requires manual cancellation of all child tasks to free resources.
CIt delays resource cleanup until the entire program exits.
DIt does not affect resource cleanup; developers must manage it explicitly.
Attempts:
2 left
💡 Hint
Think about how structured concurrency scopes child tasks to their parent.

Practice

(1/5)
1. What is the main purpose of structured concurrency in Swift?
easy
A. To group tasks so they run safely and complete before continuing
B. To allow tasks to run forever without waiting
C. To make tasks run only on the main thread
D. To avoid using async and await keywords

Solution

  1. Step 1: Understand structured concurrency concept

    Structured concurrency groups related tasks so they run safely and finish before the program moves on.
  2. Step 2: Compare options with concept

    Only To group tasks so they run safely and complete before continuing correctly describes grouping tasks to run safely and complete before continuing.
  3. Final Answer:

    To group tasks so they run safely and complete before continuing -> Option A
  4. Quick Check:

    Structured concurrency = safe grouped tasks [OK]
Hint: Structured concurrency means tasks finish before moving on [OK]
Common Mistakes:
  • Thinking tasks run forever without waiting
  • Believing tasks only run on main thread
  • Confusing structured concurrency with avoiding async/await
2. Which of the following is the correct syntax to create a task group in Swift?
easy
A. withTaskGroup(of: Int.self) { group in ... }
B. asyncGroup { ... }
C. taskGroup.run { ... }
D. TaskGroup { await ... }

Solution

  1. Step 1: Recall correct task group syntax

    Swift uses withTaskGroup(of: Type.self) { group in ... } to create a task group.
  2. Step 2: Check options for exact syntax

    Only withTaskGroup(of: Int.self) { group in ... } matches the correct syntax; others are invalid or made-up.
  3. Final Answer:

    withTaskGroup(of: Int.self) { group in ... } -> Option A
  4. Quick Check:

    Task group syntax = withTaskGroup(of:) [OK]
Hint: Task groups start with withTaskGroup(of:) [OK]
Common Mistakes:
  • Using TaskGroup without 'with'
  • Trying taskGroup.run which doesn't exist
  • Using asyncGroup which is not a Swift keyword
3. What will be the output of this Swift code using a task group?
func fetchValues() async -> [Int] {
  await withTaskGroup(of: Int.self) { group in
    group.addTask { 3 }
    group.addTask { 7 }
    group.addTask { 2 }

    var results = [Int]()
    for await value in group {
      results.append(value)
    }
    return results.sorted()
  }
}

Task {
  let values = await fetchValues()
  print(values)
}
medium
A. [3, 7, 2]
B. [2, 3, 7]
C. [7, 3, 2]
D. Compilation error

Solution

  1. Step 1: Understand task group execution

    The tasks return 3, 7, and 2 asynchronously. The for-await loop collects them in any order.
  2. Step 2: Analyze the return statement

    The results array is sorted before returning, so output is sorted ascending: [2, 3, 7].
  3. Final Answer:

    [2, 3, 7] -> Option B
  4. Quick Check:

    Sorted results = [2, 3, 7] [OK]
Hint: Remember results are sorted before printing [OK]
Common Mistakes:
  • Assuming tasks run in order added
  • Forgetting the sorting step
  • Thinking code causes compile error
4. Identify the error in this Swift code using a task group:
func calculateSum() async -> Int {
  await withTaskGroup(of: Int.self) { group in
    group.addTask { 10 }
    group.addTask { 20 }
    var total = 0
    for value in group {
      total += value
    }
    return total
  }
}
medium
A. Return type should be Void
B. Cannot add tasks inside withTaskGroup
C. Missing 'await' before 'for' loop
D. Variable 'total' should be declared outside the group

Solution

  1. Step 1: Check for correct async iteration

    When iterating over a task group, 'for await' must be used to await each task's result.
  2. Step 2: Identify missing 'await'

    The code uses 'for value in group' instead of 'for await value in group', causing a syntax error.
  3. Final Answer:

    Missing 'await' before 'for' loop -> Option C
  4. Quick Check:

    Async iteration requires 'for await' [OK]
Hint: Use 'for await' to loop over task groups [OK]
Common Mistakes:
  • Using 'for' instead of 'for await' on task groups
  • Thinking tasks can't be added inside withTaskGroup
  • Misunderstanding return type requirements
5. You want to fetch user data and user posts concurrently using structured concurrency. Which approach correctly uses a task group to run both tasks and combine their results?
hard
A. Use DispatchQueue.global().async to run tasks and wait with sleep()
B. Run tasks sequentially without a task group to avoid concurrency issues
C. Create two separate Task blocks and return results without waiting
D. Use withTaskGroup to add two tasks fetching data and posts, then await all and return combined tuple

Solution

  1. Step 1: Understand concurrency for multiple async tasks

    Structured concurrency uses task groups to run multiple async tasks concurrently and wait for all to finish.
  2. Step 2: Evaluate options for correct concurrency usage

    Use withTaskGroup to add two tasks fetching data and posts, then await all and return combined tuple correctly uses withTaskGroup to add tasks, await their completion, and combine results safely.
  3. Final Answer:

    Use withTaskGroup to add two tasks fetching data and posts, then await all and return combined tuple -> Option D
  4. Quick Check:

    Task groups run and wait for multiple tasks [OK]
Hint: Use withTaskGroup to run and wait multiple tasks [OK]
Common Mistakes:
  • Running tasks sequentially losing concurrency benefits
  • Using DispatchQueue with sleep instead of structured concurrency
  • Not waiting for tasks to finish before returning
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