【问题标题】:Invalid conversion from throwing function of type '(_, _) throws -> ()' to non-throwing function type '(JSON?, Error?) -> Void'从 '(_, _) throws -> ()' 类型的抛出函数到非抛出函数类型 '(JSON?, Error?) -> Void' 的无效转换
【发布时间】:2018-04-29 01:56:33
【问题描述】:

我有一个错误

        EduappRestClient.request(with: URLString, method: .post, parameters: parameters) { (json, error) in
        guard error == nil, let json = json else {
            completion(nil, error)
            return
        }
        let result = try JSONDecoder().decode(QuestionModel.self, from: json)
        completion(result, nil)
    }

这是我正在调用的 API,我的完整源代码可以在 https://github.com/WilliamLoke/quizApp

请问我收到这行错误代码的问题是什么?

【问题讨论】:

  • 看起来该函数需要一个不会抛出的块,但您在 do {} catch 块之外使用了 try。尝试将函数的投掷部分包装在 do catch 中,或使用 try?
  • @WilliamLoke 请阅读 Swift 书中的Error Handling 章节。

标签: ios swift alamofire swifty-json


【解决方案1】:

由于此块不会引发错误,因此您需要将 throwing 调用包装在 do catch 块中:

EduappRestClient.request(with: URLString, method: .post, parameters: parameters) { (json, error) in
    guard error == nil, let json = json else {
        completion(nil, error)
        return
    }
    do {
        let result = try JSONDecoder().decode(QuestionModel.self, from: json)
        completion(result, nil)
    } catch let error {
        completion(nil, error)
    }
}

【讨论】:

    【解决方案2】:

    我也遇到了同样的问题,解决方法很简单:你可以用try?代替try

    guard let result = try? JSONDecoder().decode(QuestionModel.self, from: json)
    

    【讨论】:

    • 解决方法太简单,劝你不要忽略DecodingErrors
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多