Makalele
Makalele

Reputation: 7521

Invalid conversion from throwing function of type '(Data) throws -> ()' to non-throwing function type '(Data) -> ()'

I've created a JSON parser and error class for it:

enum ParseError: Error {

    case cannotParseField(fieldName: String)
    case cannotFormatDate(fieldName: String)
    case cannotFormatEnum(fieldName: String)

}

class SPUserParser {

    static func parseSPUsers(data:Data) throws -> [SPUser] {
        var spUsers:[SPUser] = []
        let json = JSON(data: data)

        if let array = json["value"].array {
            for user in array {

                guard let id = user["Id"].int else { throw ParseError.cannotParseField(fieldName: "Id") }
                //PARSE OTHER STUFF...

            }
        }

        return spUsers
    }

}

Then when I'm trying to use my parser like this:

sendQuery(requestMethod: "GET", url: requestUrl, body: "", includeFormDigest:false, completed: { (data:Data) in

            var result = ""
            do {
                let newUsers:[SPUser] = try SPUserParser.parseSPUsers(data: data)
                self.spUsers.removeAll()
                self.spUsers.append(contentsOf: newUsers)
            }
            catch ParseError.cannotParseField(let fieldName) {
                result = "cannotParseField: \(fieldName)"
            }
            catch ParseError.cannotFormatDate(let fieldName) {
                result = "cannotFormatDate: \(fieldName)"
            }
            catch ParseError.cannotFormatEnum(let fieldName) {
                result = "cannotFormatEnum: \(fieldName)"
            }
            print(result)

The project won't compile.

The error is: Invalid conversion from throwing function of type '(Data) throws -> ()' to non-throwing function type '(Data) -> ()'

To fix this error I had to add catch {} after this three catches. Why I have to do this?

My code is based on Apple documentation: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

Upvotes: 0

Views: 210

Answers (1)

NlsGladiatus
NlsGladiatus

Reputation: 205

What you can do to simplify your code is using the let keyword in your catch like this :

do {
    try SPUserParser.parseSPUsers(data: data)
    // Your Stuff
} catch let parseError as ParseError {
    result = handle(parseError)
} catch {
    // Handles other kinds of errors
    result = "other kind of error: \(error)"
}

And in the handle method that I used, you check which kind of ParseError it is, basically just a switch and then handle it accordingly

func handle(_ parseError: ParseError)
    switch parseError {
    case .cannotParseField(let fieldName):
        return "cannotParseField: \(fieldName)"
    case .cannotFormatDate(let fieldName):
       return "cannotFormatDate: \(fieldName)"
    case .cannotFormatEnum(let fieldName):
        return "cannotFormatEnum: \(fieldName)"
}

Upvotes: 0

Related Questions