Stuart Breckenridge

A UIAlertController Protocol for UIViewController

The error handling model in Swift is easy to follow. For example, in the below code I am saving changes to the Core Data persistent store and if there is an error when saving a UIAlertController is displayed to the user:

do 	{ try context.managedObjectContext.save() } 
catch let error as NSError {
        let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
}

In many circumstances the above UIAlertController code is repeated in the catch blocks. To reduce this repetition I’ve created a protocol for UIViewController:

protocol UIAlertControllerErrorDisplay
{
    func showAlertControllerWithError(error:NSError)
}

extension UIViewController:UIAlertControllerErrorDisplay
{
    func showAlertControllerWithError(error:NSError)
    {
        NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
            let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

After this is implemented, you can call showAlertControllerWithError(error) from your view controller if you want to display the error message to the user. This simplifies the original code:

do {
                try context.managedObjectContext.save()
            } catch let error as NSError {
                self.showAlertControllerWithError(error)
            }

Supported by