NSError handling
Now and again we will still need to deal with NSError
. Although the Cocoa APIs are being updated for Swift very rapidly, it's likely that NSError
will be with us for some time to come. The good news is that Swift makes it very easy to do.
Anatomy of an NSError
An NSError
object has four properties of interest to us here:
- The
domain
is aString
and is used to differentiate groups of errorcodes
- The error
code
is anInt
, specific to thedomain
to which it belongs - The
userInfo
property is aDictionary
, the values of which are strings that convey any information the throwing function wants to include - The
localizedDescription
is aString
and is intended for presentation to the user; examples include"You don't have permission..."
and such
Catching NSErrors
One common framework that still returns NSErrors is the FileManager
framework, which is part of Foundation Kit. Here is an example of how to catch and deal with the errors it throws:
let url1 = URL(fileURLWithPath: "/non-existent")...