【问题标题】:Getting error when trying to use Result type with delegate尝试将 Result 类型与委托一起使用时出错
【发布时间】:2019-11-04 05:57:51
【问题描述】:

我正在尝试进行网络调用,而不是使用回调,而是尝试使用委托。使用结果类型,其中 .Sucsess 为 T:可解码且 .failure 为错误。在 .Sucsess 中传递我的模型是有效的,但是当试图传递一个错误时,我得到一个编译错误“无法推断通用参数'T'”我错过了什么?

protocol NetworkServiceDelegate: class {
    func decodableResponce<T: Decodable>(_ result: Result<T, NetworkError>)
}

let dataTask:URLSessionTask = session.dataTask(with: url) { (dataOrNil, responceOrNil, errOrNil) in
            if let error = errOrNil {
                switch error {
                case URLError.networkConnectionLost,URLError.notConnectedToInternet:
                    print("no network connection")
                    self.delegate?.decodableResponce(Result.failure(.networkConnectionLost))
                case URLError.cannotFindHost, URLError.notConnectedToInternet:
                    print("cant find the host, could be to busy, try again in a little while")
                case URLError.cancelled:
                    // if cancelled with the cancelled method the complition is still called
                    print("dont bother the user, we're doing what they want")
                default:
                    print("error = \(error.localizedDescription)")
                }
                return
            }
            guard let httpResponce:HTTPURLResponse = responceOrNil as? HTTPURLResponse
                else{
                    print("not an http responce")
                    return
            }
            guard let dataResponse = dataOrNil,
                errOrNil == nil else {
                    print(errOrNil?.localizedDescription ?? "Response Error")
                    return }
            do{
                //here dataResponse received from a network request
                let decoder = JSONDecoder()
                let modelArray = try decoder.decode([Movie].self, from:
                    dataResponse) //Decode JSON Response Data
                DispatchQueue.main.async {
                    self.delegate?.decodableResponce(Result.success(modelArray))
                }
            } catch let parsingError {
                print("Error", parsingError)
            }
            print("http status = \(httpResponce.statusCode)")
            print("completed")
        }

这一行会产生错误,如果我将 cumfirms 的枚举传递给 Error 或尝试从 dataTask 传递错误,它不会计量

self.delegate?.decodableResponce(Result.failure(.networkConnectionLost))

【问题讨论】:

    标签: swift protocols swift5


    【解决方案1】:

    嗯,您有两个问题,与“这是什么类型?”的问题有关。 Swift 对类型非常严格,所以你需要弄清楚这一点。

    • .networkConnectionLost 不是错误。这是一个错误代码。当您想要打包错误时,您需要将错误对象传递给结果。例如,URLError(URLError.networkConnectionLost) 是一个错误。

    • 短语Result&lt;T, NetworkError&gt; 没有意义。结果是已经是通用的。你的工作是解决它已经存在的泛型。您可以通过指定类型来做到这一点。

    例如,您可以声明:

    func decodableResponce(_ result: Result<Decodable, Error>)
    

    然后可以说(作为测试):

    decodableResponce(.failure(URLError(URLError.networkConnectionLost)))
    

    或者(假设电影是可解码的):

    decodableResponce(.success([Movie()]))
    

    这证明我们的类型是正确的,您可以继续围绕该示例代码构建您的实际代码。

    【讨论】:

    • 我明白了。我没有注意到这是一个“URLError.Code”而不是错误,起初它是一个返回 1 个泛型参数的函数,所以当我试图转换到“结果”类型时,我试图将泛型作为泛型返回。感谢您清除它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多