Swift Displaying Alerts best practices

Ryan Bobrowski picture Ryan Bobrowski · Apr 14, 2015 · Viewed 37.8k times · Source

I have various controllers in my app that all require validation, and when validation fails, I want to display an alert with the errors. Is there some best practice/design pattern for doing this? I could simply create a static function in a Helper class like so:

static func displayAlert(message: String, buttonTitle: String, vc: UIViewController)
{
    let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)

    let okAction = UIAlertAction(title: buttonTitle, style: .Default, handler: nil)
    alertController.addAction(okAction)

    vc.presentViewController(alertController, animated: true, completion: nil)
}

But then I need to pass the view controller..which seems like bad practice. I could shoot off a notification and observe it, but that seems like overkill. Am I overthinking this, or is there some more acceptable way to go about handling something like this?

Answer

Ryan Bobrowski picture Ryan Bobrowski · Jun 8, 2015

I ended up creating an extension for UIViewController and creating the alert function there:

extension UIViewController {
  func alert(message: String, title: String = "") {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(OKAction)
    self.present(alertController, animated: true, completion: nil)
  }  
}