0
0
Swiftprogramming~20 mins

Why modern concurrency matters in Swift - Challenge Your Understanding

Choose your learning style9 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.