How does Error work in Swift in Xcode 8 beta 4

16k Views Asked by At

Seems like when converting our old code to beta 4, I keep casting Error to NSError. That will even lead sometimes to a warning "conditional cast from 'Error' to 'NSError' always succeeds". I feel like I'm not understanding how best to use Error. I want to get to thinks like error.code, error.localizedDescription... Is there good documentation or tutorials that explains these Error changes?

For example:

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { 

Right now I'm doing something like:

if let error = error as? NSError {
 if error.code == NSURLErrorCancelled {

But that gives the warning "Conditional cast from 'Error' to 'NSError' always succeeds"

3

There are 3 best solutions below

1
On

Error is bridgeable to NSError in the same way that String is bridgeable to NSString. I.e (error as NSError) would work.

if  (error as NSError).code == NSURLErrorCancelled { 
    // code
}
2
On

Do this:

Swift 3.0 and Swift 4.0

if error._code == NSURLErrorCancelled { }
3
On

Error catching in Swift 3 has changed. Search for NSError in Release Notes. Quote:

Additionally, error types imported from Cocoa and Cocoa Touch maintain all of the information in the corresponding NSError, so it is no longer necessary to catch let as NSError to extract (for example) the user-info dictionary. Specific error types also contain typed accessors for their common user-info keys. For example:

do {
    let regex = try NSRegularExpression(pattern: "(", options: [])
} catch {
    // error is of type NSError already
    print(error.localizedDescription)
}