How are global functions defined in Swift?

Erik picture Erik · Nov 20, 2014 · Viewed 30.1k times · Source

I wrote a simple function that displays an alert when it is called. I'd like to use this function in several viewControllers. Right now I have the same bit of code copy-pasted into the bottom of each viewController, but I can't help but think there's a better way.

How can one define a function that can be called from any viewController?

Just for reference I'll paste my function below, but this is a general question. I'd like to be able to find an eloquent way to handle keyboard management identically across all view controllers as well.

func displayAlert(title:String, error:String, buttonText: String) {

    // Create the alert
    var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)

    // Add an action
    alert.addAction(UIAlertAction(title: buttonText, style: .Default, handler: { action in

        // Dismiss when the button is pressed
        self.dismissViewControllerAnimated(true, completion: nil)

    }))

    // Add it to viewController
    self.presentViewController(alert, animated: true, completion: nil)
}

Answer

Antonio picture Antonio · Nov 20, 2014

Unless you declare the function as private or fileprivate, which limit the visibility to the file or scope where it is defined, you can use it anywhere in the module if declared as internal (the default), and also from external modules if declared as public or open.

However since you say that you need it in view controllers only, why not implementing it as an extension to the view controller?

extension UIViewController {
    func displayAlert(title:String, error:String, buttonText: String) {
        ...
    }
}