Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

How are global functions defined in Swift?

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)
}
question from:https://stackoverflow.com/questions/27050580/how-are-global-functions-defined-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
        ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...