首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将类型'(Either<NestedType>) -> Void‘的值转换为预期的参数类型(Either<[_]>) -> Void’

无法将类型'(Either<NestedType>) -> Void‘的值转换为预期的参数类型(Either<[_]>) -> Void’
EN

Stack Overflow用户
提问于 2018-04-25 21:05:38
回答 1查看 528关注 0票数 1

我试图使用可编码的协议来处理API请求和响应。我正在查询的API用“结果”项下的数组进行响应:

代码语言:javascript
复制
{ results: ["id": "1", "id": "2"] }

因此,我希望构造一个嵌套的可编码类型。

从下面的代码中,使用完成处理程序中的项可以工作,但是使用NestedType或TestResponse不能工作,并返回以下错误:

代码语言:javascript
复制
Cannot convert value of type '(Either<NestedType>) -> Void' to expected argument type '(Either<[_]>) -> Void'

我不知道为什么这不起作用。尝试使用Swift 4和Swift 4.1

代码语言:javascript
复制
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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-25 21:47:11

需要声明fetch方法的完成处理程序以获取Either<[NestedType]>,而不是Either<NestedType>,因为get方法需要一个接受数组Either的完成处理程序。

顺便提一句,您称之为Either的类型,我们通常称为Result

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50031336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档