Returning Errors in Swift

Swift’s rich enumerations open up new possibilities for returning error information from functions. For example, for years Cocoa has had a convention whereby errors are returned via an out-parameter of type NSError. For example :

func executeFetchRequest(_ request: NSFetchRequest!, error error: NSErrorPointer) -> [AnyObject]!

What this method signature means is : If the method returns something, then the method succeeded and the returned something is an array; else, if the address of an NSError object pointer was supplied, make it point to an object that describes whatever error occurred. Sounds kind of like an enum to me.

Within application code, where Objective-C compatibility isn’t a concern, Swift will allow us to do this :

enum MyFetchResult
{
    case Success([AnyObject])
    case Error(NSError)
}

func myExecuteFetchRequest(_ request: NSFetchRequest!) -> MyFetchResult

...

switch (myExecuteFetchRequest(myRequest))
{
    case .Success(let results)
        // do something with results
    case .Error(let error)
        // do something with error
}

This approach has the advantage of avoiding polluting function signatures with redundant NSError arguments. Of course it does so at the cost of complicating the function result; however I think this approach will be somewhat less error-prone, especially if the function result is fed to a switch statement (like in the example above), which requires all possible values of the enum to be handled.