Consider the following Swift async function and its call. What will be printed?
func fetchNumber() async -> Int { return 42 } Task { let number = await fetchNumber() print(number) }
Remember that await waits for the async function to complete and returns the value.
The function fetchNumber() returns 42 asynchronously. Using await gets the value 42, which is then printed.
What error will this Swift code produce when run?
func fetchData() async throws -> String { throw NSError(domain: "Test", code: 1) } Task { let data = try await fetchData() print(data) }
The function throws an error but the call site does not handle it.
The fetchData() function throws an error. Since the Task does not catch it, the program crashes with a runtime error.
In Swift async testing, which statement is correct?
Think about how async test functions handle asynchronous calls.
In Swift, test functions can be marked async to allow use of await inside them. This enables proper async testing.
What will this Swift code print?
func numbers() async -> [Int] { return [1, 2, 3] } Task { let nums = await numbers() let doubled = nums.map { $0 * 2 } print(doubled) }
Remember await gets the array, then map doubles each element.
The async function returns [1, 2, 3]. After awaiting, map doubles each number, resulting in [2, 4, 6].
Given this Swift test code, why does the test finish before the async call completes?
func testAsyncCall() { Task { let result = await fetchValue() XCTAssertEqual(result, 10) } }
Think about how XCTest waits for async code to finish.
The test function is synchronous and returns immediately after starting the Task. Marking the test function async and using await on the async call ensures the test waits.