0
0
Swiftprogramming~10 mins

Testing async code in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an async function.

Swift
func fetchData() async [1] String {
    return "Data" 
}
Drag options to blanks, or click blank then click option'
A->
Bthrows
Cawait
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'async' instead of '->' to specify return type
Using 'throws' when not throwing errors
2fill in blank
medium

Complete the code to call an async function with await.

Swift
Task {
    let result = try? await [1]()
    print(result ?? "No data")
}
Drag options to blanks, or click blank then click option'
AfetchData
BfetchData()
Cawait fetchData
DTask
Attempts:
3 left
💡 Hint
Common Mistakes
Adding parentheses inside the await expression
Calling Task instead of the function
3fill in blank
hard

Fix the error in the async test function declaration.

Swift
func testFetch() [1] async throws {
    let data = try await fetchData()
    XCTAssertEqual(data, "Data")
}
Drag options to blanks, or click blank then click option'
Aasync
Bthrows
Casync throws
Doverride
Attempts:
3 left
💡 Hint
Common Mistakes
Marking only async or only throws
Forgetting to mark the test function as async
4fill in blank
hard

Fill both blanks to create a dictionary comprehension filtering async results.

Swift
let filtered = try await Dictionary(uniqueKeysWithValues: results.compactMap { item in
    guard let value = item.value, value [1] 10 else { return nil }
    return (item.key, value[2]2)
})
Drag options to blanks, or click blank then click option'
A>
B*
C**
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the guard
Using ** instead of * for multiplication
5fill in blank
hard

Fill all three blanks to create an async test that awaits and asserts a value.

Swift
func testValue() async throws {
    let value = try await [1]()
    XCTAssertEqual(value, [2])
    XCTAssertTrue(value [3] 0)
}
Drag options to blanks, or click blank then click option'
AfetchData
B"Data"
C>
DfetchNumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using fetchData instead of fetchNumber
Using wrong expected value in XCTAssertEqual