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