我收到此错误并且不知道如何解决它。即使试图澄清泛型类型似乎也不起作用。任何解决方案都会有所帮助,因为Swift编译器真的不会让我继续下去。
这是我的功能:
public func request<T: JSONEncodable, K: JSONDecodable>(_ url: URLConvertible, httpMethod: HTTPMethod, query: [URLQueryItem]? = nil, body: T? = nil, completion: @escaping (Result<K>) -> Void) {
do {
var urlRequest = try buildURLRequest(httpMethod: httpMethod, url: url, withBase: baseURL, query: query, body: body)
for middleware in requestMiddleware {
try middleware.run(request: &urlRequest)
}
session.dataTask(with: urlRequest, completionHandler: { (data, urlResponse, error) in
do {
var data = data
var urlResponse = urlResponse
var error = error
for middleware in self.responseMiddleware {
try middleware.run(data: &data, urlResponse: &urlResponse, error: &error)
}
if let error = error {
throw error
} else if let data = data {
completion(.success(urlResponse as! HTTPURLResponse, try self.jsonDecoder.decode(K.self, from: data)))
} else {
completion(.failure(HTTPClientError.nilResponseData))
}
} catch {
completion(.failure(error))
}
}).resume()
} catch {
completion(.failure(error))
}
}
结果枚举:
internal enum Result<T: JSONDecodable> {
case success(HTTPURLResponse, T)
case failure(Error)
}
以及我如何称呼它:
httpClient.request("hi", httpMethod: .get, completion: { (result: Result<Model>) -> Void in
switch result {
case .success(httpURLResponse, value):
print("nice")
case .failure(error):
print("nice")
}
})
答案 0 :(得分:0)
错误是因为body: T? = nil
。编译器无法解析通用T
。您必须提供确认协议JSONEncodable
的正文。
例如
struct ExampleBody: JSONEncodable {
}
现在
let body: ExampleBody = Body()
httpClient.request("hi", httpMethod: .get, body:body, completion: { (result: Result<Model>) -> Void in
switch result {
case .success(httpURLResponse, value):
print("nice")
case .failure(error):
print("nice")
}
})
或者,因为您只是将身体传递给buildURLRequest
,您不需要T
public func request<K: JSONDecodable>(_ url: URLConvertible, httpMethod: HTTPMethod, query: [URLQueryItem]? = nil, body: JSONEncodable? = nil, completion: @escaping (Result<K>) -> Void) {
//....
}