[英]Cannot convert value of type 'Void' to expected argument type '(String) -> Void'
[英]Cannot convert value of type '(Either<NestedType>) -> Void' to expected argument type '(Either<[_]>) -> Void'
我正在嘗試將Codable與協議配合使用以處理API請求和響應。 我正在查詢的API在鍵“結果”下以一系列項響應:
{ results: ["id": "1", "id": "2"] }
因此,我希望構造一個嵌套的Codable類型。
從下面的代碼中,可以在完成處理程序中使用Items,但不能使用NestedType或TestResponse,並返回以下錯誤:
Cannot convert value of type '(Either<NestedType>) -> Void' to expected argument type '(Either<[_]>) -> Void'
我不確定為什么這行不通。 嘗試使用Swift 4和Swift 4.1
import Foundation
enum Either<T> {
case success(T)
case error(Error)
}
enum APIError: Error {
case unknown, badResponse, jsonDecoder
}
protocol APIClient {
var session: URLSession { get }
func get<T: Codable>(with request: URLRequest, completion: @escaping (Either<[T]>) -> Void)
}
extension APIClient {
var session: URLSession {
return URLSession.shared
}
func get<T: Codable>(with request: URLRequest, completion: @escaping (Either<[T]>) -> Void) {
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
completion(.error(error!))
return
}
guard let response = response as? HTTPURLResponse, 200..<300 ~= response.statusCode else {
completion(.error(APIError.badResponse))
return
}
guard let value = try? JSONDecoder().decode([T].self, from: data!) else {
completion(.error(APIError.jsonDecoder))
return
}
DispatchQueue.main.async {
completion(.success(value))
}
}
task.resume()
}
}
class TestClient: APIClient {
func fetch(with endpoint: TestEndpoint, completion: @escaping (Either<NestedType>) -> Void) {
let request = endpoint.request
print(request.allHTTPHeaderFields)
print("endpoint request", endpoint)
get(with: request, completion: completion)
}
}
typealias Items = [SingleItem]
typealias NestedType = TestResponse
struct TestResponse: Codable {
let result: [SingleItem]
}
struct SingleItem: Codable {
let id: String
}
您需要聲明fetch
方法的完成處理程序采用Either<[NestedType]>
,而不是Either<NestedType>
,因為get
方法需要使用采用數組Either
的完成處理程序。
順便說一句,您稱為Either
的類型,我們通常稱為Result
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.