我需要將如下函式從庫中包裝到異步函式中。我的第一次試用的錯誤如下:
呼叫中缺少引數“errorHandler”的引數。
我怎樣才能正確包裝它?您的意見將不勝感激。
原始功能:
func createConverter(id: String, successHandler: @escaping (Converter) -> Void, errorHandler: @escaping (Error) -> Void) -> Cancellable
func createConverter(id: String) async throws -> Converter {
return await withCheckedThrowingContinuation({
(continuation: CheckedContinuation<Converter, Error>) in
createConverter(id: id) { result in
switch result {
case .success(let converter):
continuation.resume(returning: converter)
case .failure(let error):
continuation.resume(throwing: error)
}
}
})
}
uj5u.com熱心網友回復:
由于原始createConverter有三個引數,因此您需要提供所有三個引數。你錯過了第三個。您的嘗試假設只有一個閉包引數(型別Result<Converter, Error>)而不是兩個單獨的閉包引數。
您還應該try在await.
func createConverter(id: String) async throws -> Converter {
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Converter, Error>) in
let cancellable = createConverter(id: id) { (converter: Converter) in
continuation.resume(returning: converter)
} errorHandler: { error in
continuation.resume(throwing: error)
}
}
}
這可以編譯,但我無法驗證結果。這也沒有使用 original 的原始Cancellable回傳值createConverter。
由于我沒有您擁有的任何庫,因此已在 Playground 中使用以下方法進行了驗證:
import Combine
// Dummy
struct Converter {
}
// Original function
func createConverter(id: String, successHandler: @escaping (Converter) -> Void, errorHandler: @escaping (Error) -> Void) -> Cancellable {
return AnyCancellable { // Just enough so it compiles
}
}
// New function
func createConverter(id: String) async throws -> Converter {
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Converter, Error>) in
let cancellable = createConverter(id: id) { (converter: Converter) in
continuation.resume(returning: converter)
} errorHandler: { error in
continuation.resume(throwing: error)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/533055.html
上一篇:如何將結構陣列傳遞給CAPI?
