无法将类型"Swift.String"(0x10fef45c0)的值转换为"Swift.Error"(0x10ff2bd10)。(分行)



下面的代码行产生错误,

DispatchQueue.main.async { completion(.success(jsonData(, Error as!错误( }

打印时jsonData此代码返回数组的完美结果,但收到此错误,

无法将类型"Swift.String"(0x10fef45c0(的值转换为"Swift.Error"(0x10ff2bd10(。(分行(

正如错误所说,我知道这是一个强制转换异常,但我无法修改代码以使其工作。我对 Swift 有点陌生,所以任何帮助将不胜感激。下面是我的

import Foundation
class APIService {

private var dataTask: URLSessionDataTask?

func getPopularPosts(completion: @escaping (Result<Any, Error>, Error) -> Void) {

let popularURL = "URL Here"

guard let url = URL(string: popularURL) else {return}

// Create URL Session - work on the background
dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in

// Handle Error
if let error = error {
completion(.failure(error), Error.self as! Error)
print("DataTask error: (error.localizedDescription)")
return
}

guard let response = response as? HTTPURLResponse else {
// Handle Empty Response
print("Empty Response")
return
}
print("Response status code: (response.statusCode)")

guard let data = data else {
// Handle Empty Data
print("Empty Data")
return
}

do {
// Parse the data
let decoder = JSONDecoder()
let jsonData = try decoder.decode(APIService.self, from: data)
// print(jsonData)
// Back to the main thread
DispatchQueue.main.async {
completion(.success(jsonData), Error as! Error)
}
} catch let error {
completion(.failure(error),error)
}

}
dataTask?.resume()
}
}

修改完成块参数,您已经在Result.failure(Error)块中返回了错误,因此无需再次将其作为完成参数中的另一个参数重复。 以下是解决此问题的方法:

声明:

class APIService {
private var dataTask: URLSessionDataTask?
func getPopularPosts(completion: @escaping (Result<CategoriesNewsData, Error>) -> Void) {
let popularURL = "URL Here"
guard let url = URL(string: popularURL) else {return}
// Create URL Session - work on the background
dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in
// Handle Error
if let error = error {
completion(.failure(error))
print("DataTask error: (error.localizedDescription)")
return
}
guard let response = response as? HTTPURLResponse else {
// Handle Empty Response
print("Empty Response") // Throw a custom error here too.
return
}
print("Response status code: (response.statusCode)")
guard let data = data else {
// Handle Empty Data
print("Empty Data") // Throw a custom error here too.
return
}
do {
let decoder = JSONDecoder()
let jsonData = try decoder.decode(CategoriesNewsData.self, from: data)
DispatchQueue.main.async {
completion(.success(jsonData))
}
} catch let error {
completion(.failure(error))
}
}
dataTask?.resume()
}
}

叫:

service.getPopularPosts { result in
switch result {
case .success(let categoriesNewsData):
print(categoriesNewsData)
case .failure(let error):
print(error)
}
}

相关内容

  • 没有找到相关文章

最新更新