0
0
Swiftprogramming~20 mins

Testing async code in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Async Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this async function call?

Consider the following Swift async function and its call. What will be printed?

Swift
func fetchNumber() async -> Int {
    return 42
}

Task {
    let number = await fetchNumber()
    print(number)
}
A0
Bnil
C42
DCompilation error
Attempts:
2 left
💡 Hint

Remember that await waits for the async function to complete and returns the value.

Predict Output
intermediate
2:00remaining
What error does this async function cause?

What error will this Swift code produce when run?

Swift
func fetchData() async throws -> String {
    throw NSError(domain: "Test", code: 1)
}

Task {
    let data = try await fetchData()
    print(data)
}
ARuntime error: unhandled error
BCompilation error: missing try
CPrints empty string
DNo error, prints data
Attempts:
2 left
💡 Hint

The function throws an error but the call site does not handle it.

🧠 Conceptual
advanced
2:00remaining
Which statement about async testing is true?

In Swift async testing, which statement is correct?

AYou must use <code>await</code> inside test functions marked with <code>async</code>.
BAsync functions cannot be tested with XCTest.
CAsync tests run synchronously by default.
DYou cannot use <code>Task</code> inside test functions.
Attempts:
2 left
💡 Hint

Think about how async test functions handle asynchronous calls.

Predict Output
advanced
2:00remaining
What is the output of this async sequence processing?

What will this Swift code print?

Swift
func numbers() async -> [Int] {
    return [1, 2, 3]
}

Task {
    let nums = await numbers()
    let doubled = nums.map { $0 * 2 }
    print(doubled)
}
A[1, 2, 3]
B[2, 4, 6]
CCompilation error: cannot use map here
DRuntime error: await on non-async context
Attempts:
2 left
💡 Hint

Remember await gets the array, then map doubles each element.

🔧 Debug
expert
2:00remaining
Why does this async test fail to wait for completion?

Given this Swift test code, why does the test finish before the async call completes?

Swift
func testAsyncCall() {
    Task {
        let result = await fetchValue()
        XCTAssertEqual(result, 10)
    }
}
AfetchValue() is not an async function.
BThe <code>await</code> keyword is missing inside the Task.
CXCTAssertEqual cannot be used inside Task closures.
DThe test function is not marked async, so it does not wait for Task to finish.
Attempts:
2 left
💡 Hint

Think about how XCTest waits for async code to finish.