William Loke
William Loke

Reputation: 377

Invalid conversion from throwing function of type '(_, _) throws -> ()' to non-throwing function type '(JSON?, Error?) -> Void'

I am having an error of

        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)
    }

it's an API i am calling and my full source code can be found at https://github.com/WilliamLoke/quizApp

may i know what is the issue i am getting this line of error code?

Upvotes: 0

Views: 4114

Answers (2)

swifthing
swifthing

Reputation: 550

I've got the same problem, and the solution is easy: you can just use try? instead of try

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

Upvotes: 0

dalton_c
dalton_c

Reputation: 7171

Since this block is not expected to throw an error, you need to wrap your throwing call in a do catch block:

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)
    }
}

Upvotes: 1

Related Questions