我试图使用可编码的协议来处理API请求和响应。我正在查询的API用“结果”项下的数组进行响应:
{ results: ["id": "1", "id": "2"] }因此,我希望构造一个嵌套的可编码类型。
从下面的代码中,使用完成处理程序中的项可以工作,但是使用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
}发布于 2018-04-25 21:47:11
需要声明fetch方法的完成处理程序以获取Either<[NestedType]>,而不是Either<NestedType>,因为get方法需要一个接受数组Either的完成处理程序。
顺便提一句,您称之为Either的类型,我们通常称为Result。
https://stackoverflow.com/questions/50031336
复制相似问题