ConcurrencyMidMCQ
What is `withCheckedContinuation` and why is it needed?
Test your knowledge:
Explanation & Code
Answer:
withCheckedContinuation bridges old callback-based APIs into the async/await world. Use it to wrap any completion-handler function so it can be awaited.
Code Example:
// Old callback-based API
func fetchData(completion: @escaping (Data?, Error?) -> Void) { ... }
// Wrap it for async/await use
func fetchData() async throws -> Data {
try await withCheckedThrowingContinuation { continuation in
fetchData { data, error in
if let error = error {
continuation.resume(throwing: error)
} else if let data = data {
continuation.resume(returning: data)
}
}
}
}
// Now you can await it
let data = try await fetchData()
Key Rules:
continuation.resume()must be called exactly once — never zero, never twice- Use
withCheckedThrowingContinuationwhen the operation can fail withUnsafeContinuationskips the "called once" check — only use if performance is critical
Rate your understanding: