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)
}
Swift Function Declarationfunc - keyword used to declare a function. functionName - any name given to the function. parameters - any value passed to function. returnType - specifies the type of value returned by the function.
Global functions allow you to perform processing at a specific resolution and extent. By default, global functions process rasters at the source resolution and full extent. This means that applying a global function may take some time, depending on the size of the outputs.
Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.
What you are calling global function is usually called a free function and they are A Good Thing. You would define it just like a class' member function, but outside of that class' scope. double squared(double x); and put the implementation (first example) into the *.
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) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With