0

I have an app with a large number of ViewControllers. There is also a collection of functions that return UIAlertControllers informing the user regarding events related to his account. Here is an example of one such funtion:

func signInSuccessAlert() -> UIAlertController {
        //signInSuccessAlert
        let signInSuccessAlert = UIAlertController(title: "Success", message: "You have been successfully signed in!", preferredStyle: .alert)
        signInSuccessAlert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
        return signInSuccessAlert
    }

My goal is to then be able to display these UIAlertControllers in one line. Like so:

present(signInSuccessAlert(), animated: true, completion: nil)

What is the best way to make these functions available only to the ViewControllers that need them? As opposed to declaring them globally.

Marmelador
  • 947
  • 7
  • 27
  • 1
    Make a protocol declaring them. Then implement them in the protocol's extension. Any ViewController that needs access should conform to the protocol. – AgRizzo Jul 16 '17 at 13:52

1 Answers1

0

You could create an extension of UIViewController and declare all those functions there. Something like this:

extension UIViewController
{

    func signInSuccessAlert() -> UIAlertController {
        //signInSuccessAlert
        let signInSuccessAlert = UIAlertController(title: "Success", message: "You have been successfully signed in!", preferredStyle: .alert)
        signInSuccessAlert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
        return signInSuccessAlert
    }

}

This way all your viewcontrollers will have access to these functions. If you want want to give access only to some viewcontrollers you will have to use protocols like AgRizzo suggested in the comment.

Nikita Gaidukov
  • 771
  • 4
  • 14