Challenge - 5 Problems
Swift Async Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of an async function call with await
What is the output of this Swift code when run in an async context?
Swift
func fetchNumber() async -> Int { return 42 } Task { let result = await fetchNumber() print(result) }
Attempts:
2 left
💡 Hint
Remember to use 'await' when calling async functions inside async contexts.
✗ Incorrect
The async function 'fetchNumber' returns 42. Using 'await' inside the Task closure correctly waits for the result, so it prints 42.
❓ Predict Output
intermediate2:00remaining
Return type of async function
What is the type of the variable 'value' after this code runs?
Swift
func getString() async -> String { return "Hello" } Task { let value = await getString() print(type(of: value)) }
Attempts:
2 left
💡 Hint
The 'await' keyword unwraps the async result to its return type.
✗ Incorrect
The async function returns a String. Awaiting it gives a String, so 'value' is of type String.
❓ Predict Output
advanced2:00remaining
Async function with throwing error
What will be printed when this code runs?
Swift
enum MyError: Error { case failed } func riskyTask() async throws -> String { throw MyError.failed } Task { do { let result = try await riskyTask() print(result) } catch { print("Error caught") } }
Attempts:
2 left
💡 Hint
Async functions that throw must be called with 'try await' inside a do-catch block.
✗ Incorrect
The function throws an error, which is caught by the catch block, so it prints 'Error caught'.
🧠 Conceptual
advanced2:00remaining
Correct async function declaration
Which of the following is the correct way to declare an async function in Swift that returns an integer?
Attempts:
2 left
💡 Hint
The 'async' keyword goes after the function parentheses.
✗ Incorrect
In Swift, the 'async' keyword is placed after the parameter list and before the return arrow.
❓ Predict Output
expert3:00remaining
Async function call order and output
What is the output of this Swift code?
Swift
func first() async -> String { return "First" } func second() async -> String { return "Second" } Task { async let a = first() async let b = second() let result = await a + " & " + await b print(result) }
Attempts:
2 left
💡 Hint
async let allows concurrent execution; awaiting each unwraps the result.
✗ Incorrect
Both async lets run concurrently. Awaiting them unwraps their results, concatenating to 'First & Second'.