When refactoring old closure-based code to new Swift concurrency it is inevitable that you come accross scenario where you need to call withCheckedThrowingContinuation where enclosing method has no return value. In that case, you should get error in Xcode: Generic parameter ’T’ could not be inferred

Let’s consider the following block of code

func fetchData() async throws {
    try await withCheckedThrowingContinuation({ continuation in
        URLSession.shared.dataTask(with: URL(string: "https://example.com")!) { data, response, error in
            if let error = error {
                continuation.resume(throwing: error)
                return
            }
            continuation.resume()
        }.resume()
    })
}

This code produces the error above because withCheckedThrowingContinuation method has generic parameter which compiler usuallly infers from return value of enclosing method. However, our enclosing method fetchData has no return value thus compiler raises the error.

Fortunately the fix is incredibly simple, just cast return type to Void

func fetchData() async throws {
    try await withCheckedThrowingContinuation({ continuation in
        URLSession.shared.dataTask(with: URL(string: "https://example.com")!) { data, response, error in
            if let error = error {
                continuation.resume(throwing: error)
                return
            }
            continuation.resume()
        }.resume()
    }) as Void
}

It is important to note that this approach works for all methods not just for withCheckedThrowingContinuation or other methods specific to Swift concurrency.