Bird
Raised Fist0
Swiftprogramming~20 mins

Why modern concurrency matters in Swift - Challenge Your Understanding

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 task execution order
What is the output of this Swift code using async/await and Task groups?
Swift
import Foundation

func fetchNumber(_ n: Int) async -> Int {
    try? await Task.sleep(n * 100_000_000) // sleep n*0.1 seconds
    return n
}

func test() async {
    await withTaskGroup(of: Int.self) { group in
        for i in 1...3 {
            group.addTask {
                await fetchNumber(i)
            }
        }
        for await result in group {
            print(result)
        }
    }
}

Task {
    await test()
}

RunLoop.main.run()
A1\n2\n3
BCompilation error due to missing await
CThe numbers 1, 2, 3 printed in any order
D3\n2\n1
Attempts:
2 left
💡 Hint
Think about how Task groups run tasks concurrently and how results arrive.
🧠 Conceptual
intermediate
1:30remaining
Why use structured concurrency?
Which of the following best explains why structured concurrency is important in modern Swift concurrency?
AIt helps manage the lifecycle of concurrent tasks to avoid leaks and unexpected behavior.
BIt replaces all synchronous code with asynchronous code automatically.
CIt allows launching infinite background threads without limits.
DIt makes all code run faster by parallelizing everything.
Attempts:
2 left
💡 Hint
Think about how tasks are organized and cleaned up.
🔧 Debug
advanced
2:00remaining
Identify the concurrency bug
What error or problem will this Swift code cause when run?
Swift
var sharedCounter = 0

func increment() async {
    for _ in 1...1000 {
        sharedCounter += 1
    }
}

Task {
    await increment()
}
Task {
    await increment()
}

Task.sleep(1_000_000_000) // wait 1 second
print(sharedCounter)
APrints 2000 as expected
BPrints a number less than 2000 due to race condition
CCompilation error because sharedCounter is not @MainActor
DRuntime crash due to data race detected by Swift
Attempts:
2 left
💡 Hint
Think about what happens when two tasks modify the same variable without synchronization.
📝 Syntax
advanced
1:30remaining
Which code compiles without error?
Which of these Swift concurrency snippets compiles without error?
Afunc foo() async -> Int { return await bar() } func bar() async -> Int { 42 }
Bfunc foo() async -> Int { return 42 }
Cfunc foo() async -> Int { return await bar() } func bar() -> Int { 42 }
Dfunc foo() -> Int { return await bar() } func bar() async -> Int { 42 }
Attempts:
2 left
💡 Hint
Remember async functions can only await other async functions.
🚀 Application
expert
2:30remaining
How many tasks run concurrently?
Given this Swift code, how many tasks run concurrently at the peak?
Swift
import Foundation

func work(id: Int) async {
    print("Start \(id)")
    try? await Task.sleep(500_000_000) // 0.5 seconds
    print("End \(id)")
}

func main() async {
    await withTaskGroup(of: Void.self) { group in
        for i in 1...5 {
            group.addTask {
                await work(id: i)
            }
            if i == 3 {
                try? await Task.sleep(600_000_000) // 0.6 seconds
            }
        }
    }
}

Task {
    await main()
}

RunLoop.main.run()
AOnly 1 task runs at a time due to the sleep inside the loop
B2 tasks run concurrently because the sleep pauses task addition
C3 tasks run concurrently at peak because of the sleep after adding 3 tasks
D5 tasks run concurrently at the same time
Attempts:
2 left
💡 Hint
Task groups start tasks immediately; sleeps inside the loop do not block running tasks.

Practice

(1/5)
1. What is the main benefit of using modern concurrency with async and await in Swift?
easy
A. It makes your app use more memory.
B. It allows your app to do many tasks at the same time without freezing.
C. It slows down your app to avoid errors.
D. It removes the need for functions.

Solution

  1. Step 1: Understand what concurrency means

    Concurrency means doing multiple tasks at once, which helps apps stay responsive.
  2. Step 2: Connect concurrency with async and await

    These keywords let Swift run tasks without waiting and freezing the app.
  3. Final Answer:

    It allows your app to do many tasks at the same time without freezing. -> Option B
  4. Quick Check:

    Modern concurrency = smooth multitasking [OK]
Hint: Remember: async/await = multitasking without freezing [OK]
Common Mistakes:
  • Thinking concurrency slows the app down
  • Confusing concurrency with more memory use
  • Believing async/await removes functions
2. Which of the following is the correct way to declare an asynchronous function in Swift?
easy
A. func fetchData() async -> String
B. async func fetchData() -> String
C. func async fetchData() -> String
D. func fetchData() -> async String

Solution

  1. Step 1: Recall Swift async function syntax

    In Swift, async comes after the function parentheses.
  2. Step 2: Check each option's syntax

    Only func fetchData() async -> String places async correctly after the parentheses.
  3. Final Answer:

    func fetchData() async -> String -> Option A
  4. Quick Check:

    async keyword after () = correct syntax [OK]
Hint: Put async right after () in function declaration [OK]
Common Mistakes:
  • Placing async before func
  • Inserting async inside parameter list
  • Putting async before return type
3. What will be printed by this Swift code using async/await?
func fetchNumber() async -> Int {
    return 10
}

Task {
    let number = await fetchNumber()
    print(number)
}
medium
A. Nothing prints
B. await fetchNumber()
C. Error: missing await
D. 10

Solution

  1. Step 1: Understand async function behavior

    The function fetchNumber() returns 10 asynchronously.
  2. Step 2: Check how Task and await work

    The Task runs the async code, and await waits for the result before printing.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    await fetchNumber() returns 10 [OK]
Hint: await waits for async result before printing [OK]
Common Mistakes:
  • Forgetting to use await
  • Expecting print before result is ready
  • Thinking async functions run instantly
4. Identify the error in this Swift async code:
func loadData() async -> String {
    return "Data"
}

func printData() {
    let result = await loadData()
    print(result)
}
medium
A. loadData should not be async
B. await cannot be used inside printData
C. Missing async keyword in printData function declaration
D. printData should return String

Solution

  1. Step 1: Check where await is used

    The function printData() uses await inside its body.
  2. Step 2: Confirm async requirement for await

    Any function using await must be marked async.
  3. Final Answer:

    Missing async keyword in printData function declaration -> Option C
  4. Quick Check:

    await requires async function [OK]
Hint: Add async to any function using await [OK]
Common Mistakes:
  • Not marking function async when using await
  • Thinking await can be used in normal functions
  • Confusing async with return type
5. You want to fetch user data and user posts concurrently in Swift using async/await. Which approach best uses modern concurrency to improve speed?
hard
A. Use async let to start both fetchUser() and fetchPosts() at the same time, then await both results.
B. Run fetchUser() synchronously, then fetchPosts() asynchronously.
C. Call fetchUser() and fetchPosts() one after another with await each time.
D. Use DispatchQueue without async/await to run both tasks.

Solution

  1. Step 1: Understand sequential vs concurrent calls

    Calling await one after another waits for the first to finish before starting the second.
  2. Step 2: Use async let for concurrency

    Using async let starts both tasks simultaneously, improving speed.
  3. Final Answer:

    Use async let to start both fetchUser() and fetchPosts() at the same time, then await both results. -> Option A
  4. Quick Check:

    async let = concurrent tasks [OK]
Hint: Use async let to run tasks together, then await results [OK]
Common Mistakes:
  • Awaiting tasks one by one causing delay
  • Mixing synchronous and asynchronous calls incorrectly
  • Using old concurrency methods instead of async/await
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