Challenge - 5 Problems
Async Await Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this async function call?
Consider the following Swift code using async/await. What will be printed when running this code?
Swift
func fetchNumber() async -> Int { return 42 } func printNumber() async { let number = await fetchNumber() print("Number is \(number)") } Task { await printNumber() }
Attempts:
2 left
💡 Hint
Remember to use await when calling async functions to get their result.
✗ Incorrect
The function fetchNumber returns 42 asynchronously. The printNumber function awaits fetchNumber and prints the result. The output is 'Number is 42'.
❓ Predict Output
intermediate2:00remaining
What happens if you omit await when calling an async function?
Look at this Swift code snippet. What error or output will it produce?
Swift
func fetchText() async -> String { return "Hello" } func test() { let text = fetchText() print(text) } test()
Attempts:
2 left
💡 Hint
Async functions must be awaited or called from async context.
✗ Incorrect
Calling an async function without await in a synchronous function causes a compilation error in Swift.
🔧 Debug
advanced2:30remaining
Why does this async function not print the expected result?
Examine the code below. It is supposed to print "Result: 10" but prints nothing. What is the reason?
Swift
func calculate() async -> Int { return 10 } func run() { Task { let value = await calculate() print("Result: \(value)") } } run()
Attempts:
2 left
💡 Hint
Consider the lifecycle of asynchronous tasks and the main thread.
✗ Incorrect
The run() function starts a Task but returns immediately. The program may exit before the Task finishes, so print is never seen.
📝 Syntax
advanced2:00remaining
Which option correctly awaits an async function inside a synchronous function?
Given an async function fetchData(), which code snippet correctly calls it from a synchronous function?
Swift
func fetchData() async -> String { return "Data" } func syncCaller() { // Which option is correct here? }
Attempts:
2 left
💡 Hint
You cannot use await directly in synchronous functions, but you can start a Task.
✗ Incorrect
Option A uses Task to run async code inside a synchronous function. Option A is invalid syntax, C is not a Swift method, D ignores async nature.
🚀 Application
expert3:00remaining
How many times will the print statement execute in this async sequence?
Analyze the code below. How many times will "Done" be printed?
Swift
func delayedPrint() async { for i in 1...3 { await Task.sleep(UInt64(500_000_000)) // 0.5 seconds print("Done") } } Task { await delayedPrint() }
Attempts:
2 left
💡 Hint
The loop runs 3 times with a delay before each print.
✗ Incorrect
The for loop runs 3 times, each time awaiting 0.5 seconds then printing "Done". So output is printed 3 times.