尝试使用最新的Swift 5.0 Result类。做了一个通用的功能但是调用它不会编译。为此有不同的语法吗? XCode在这里没有提出建议。
private func buildTask<T: Decodable>(request:URLRequest, handler: @escaping (Result<T, NetworkError>) -> Void) -> URLSessionDataTask {
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// logic here....
let decoder = JSONDecoder()
if let data = data, let decodedResponse = try? decoder.decode(T.self, from: data) {
handler(.success(decodedResponse))
} else {
handler(.failure(.errorParsing))
}
}
return task
}
// calling method, Compile error here about generic
func test() {
let url:URL = URL(string: "http://google.com")!
let request:URLRequest = URLRequest(url: url)
let task = buildTask<String>(request: request) { (result) in
switch result {
case .success:
print("good")
case .failure:
print("bad")
}
}
}
//海报下方的解决方案。
let task = buildTask(request: request) { (result:Result<String, NetworkError>) in
switch result {
case .success(let success):
print("success \(success)")
case .failure(let error):
print("error \(error)")
}
}
答案 0 :(得分:2)
在Swift中,调用时不能使用<T>
指定泛型。泛型方法的类型是从您传递给它的类型中推断出来的。在这种情况下,从handler
闭包开始:
let task = buildTask(request: request) { (result: Result<String, NetworkError>) in
当您指定result
的类型时,编译器可以推断闭包的类型,然后推断方法的泛型。