Thrown expression type 'Error?' does not conform to 'Error' swift 3

Viewed 4159

Changing my playground code to Swift 3, Xcode suggested changing

if let requestError = error {
    completion({throw (Error(code: requestError._code, description: requestError.localizedDescription, innerError: nil, informations:nil))})
}

to

if let requestError = error {
    completion({throw (Error(code: requestError._code, description: requestError.localizedDescription, innerError: nil, informations:nil)) as! Error})
}

But I get this error: "'Error' is not convertible to 'Error'; did you mean to use 'as!' to force downcast?"

1 Answers

Error handling in Swift 3 is different. Error is now a protocol that you conform to, so you define your error cases and then throw.

enum NetworkError: Error {
    case unauthorised
    case timeout
    case serverError
    case invalidResponse
}

guard let httpUrlResponse = response as? HTTPURLResponse else {
   throw NetworkError.invalidResponse
}

For more information please see the Official Documentation

Related