【发布时间】:2019-08-30 01:20:43
【问题描述】:
我正在重构我的代码,让一切变得更干净。我向我的 API 发出请求,并且可以期待不同类型的返回值,因此我创建了一个通用函数来简化我的代码。
我希望这个函数抛出,所以我可以简单地使用do catch 来处理不同类型的错误或成功案例。
这是我的功能:
func performRequest<T: Codable>(_ request: URLRequest, ofType: T.Type) throws -> T{
URLSession.shared.dataTask(with: request) {(data, response, err) in
if let err = err {throw err}
if let response = response as? HTTPURLResponse {
if response.statusCode != 200 {
// Here I would return the value
} else {
// here I would throw the error
}
}
}.resume()
}
但是在URLSession.shared.dataTask 之后的第一行我得到了这个错误:
从'(_, _, _) throws -> ()' 类型的抛出函数到非抛出函数类型'(Data?, URLResponse?, Error?) -> Void'的无效转换
我明白那是因为我试图在 dataTask 函数中抛出,但我的问题是,有没有办法做到这一点?
【问题讨论】:
-
您不能在
URLSession.shared.dataTask的完成处理程序中使用throw,因为该完成处理程序的类型已经定义并且它不是throws函数。