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
domainis aStringand is used to differentiate groups of errorcodes - The error
codeis anInt, specific to thedomainto which it belongs - The
userInfoproperty is aDictionary, the values of which are strings that convey any information the throwing function wants to include - The
localizedDescriptionis aStringand 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")...