2

I'm trying to make my life a little bit easier and my app more maintainable while at the same time reducing the amount of duplicated code. So I thought it would be nice to put the some code to display a certain type of UIAlertController into its own class.

The thing is, that I have basically the same alert which only differs really slightly based on where I display it in my app. So I thought to myself: why not use a enum and every time I want to display an alert of that kind, just give it the enum value. Get rid of all the duplicated strings everywhere in my code.

I love enums in Swift. They are just so schwifty - ehh I mean swifty. So I came up with this example enum:

enum MyAlertType {
    case a
    case b
}

Next I created a simple class to handle the display:

class MyAlert {
    static func showAlert(ofType type: MyAlertType, inViewController viewController: UIViewController, handler: ((UIAlertAction) -> ())? = nil, completion: (() -> ())? = nil) {

        var message: String
        switch type {
        case .a:
            message = "A is a nice letter!"
        case .b:
            message = "B is a nice letter!"
        }

        let alert = UIAlertController(title: "Do you know which letter is nice?", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))
        viewController.present(alert, animated: true, completion: completion)
    }
}

//Somewhere in my code (obviously a UIViewController)
MyAlert.showAlert(ofType: .a), inViewController: self)

But wait, I still have to give this function the ViewController where I want to display the alert in. For me thats always the same (self) so the next logical step was to make this an extension:

extension UIViewController {
    func showAlert(ofType type: MyAlertType, handler: ((UIAlertAction) -> ())? = nil, completion: (() -> ())? = nil) {

        var message: String
        switch type {
        case .a:
            message = "A is a nice letter!"
        case .b:
            message = "B is a nice letter!"
        }

        let alert = UIAlertController(title: "Do you know which letter is nice?", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))
        present(alert, animated: true, completion: completion)
    }
}

//Somewhere in my UIViewController)
showAlert(ofType: .a)

But this makes the code available for all UIViewControllers, even those where I don't explicitly need/want to display that kind of alert. I mean, yeah sure, I am the developer and I can decide not to use this but on the other hand isn't it always a good practice to hide everything as much as possible and as least as necessary? Who knows who might in the future join my dev team and start misusing my beautiful code in ways I haven't thought of?

The other day I learned about Swifts protocol oriented programming approach (which to be honest I still have not fully understood by now) and now I think, I maybe should make this a protocol with a default implementation and then let the only those UIViewControllers implement the protocol, where I need to show this alert.

protocol MyAlertProtocol {
    func showAlert(ofType type: MyAlertType, handler: ((UIAlertAction) -> ())?, completion: (() -> ())?)
}

extension MyAlertProtocol where Self : UIViewController {
    func showAlert(ofType type: MyAlertType, handler: ((UIAlertAction) -> ())? = nil, completion: (() -> ())? = nil) {

        var message: String
        switch type {
        case .a:
            message = "A is a nice letter!"
        case .b:
            message = "B is a nice letter!"
        }

        let alert = UIAlertController(title: "Do you know which letter is nice?", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))
        present(alert, animated: true, completion: completion)
    }
}

extension MyViewController: MyAlertProtocol {}

I know that this might sound as an opinion based question so I'm not asking you if you think if this or that is better but to tell me if there actually is a best practice for this scenario and how it looks like.

Protocol with default implementation via protocol extension? Simple UIViewController extension? Custom Enum, Struct or Class with static function (and if so, which one)? Or maybe even just a function somewhere in a Swift file? I feel overwhelmed. The agony of choice...

UPDATE/SOLUTION

After reading the given answers, I decided that my Sergeys answer was indeed the most suitable one. I wanted to make my like "easier" by having "less lines of duplicated code". For me this included the "presend(controller:animated:)" inside my ViewController.

However, I think you guys are right. I should use a struct (a class is really not necessary for one static function) with a static func to generate the alert man make it "ready to use" but still let the caller decide where to present it.

By doing it like this, I could use my alert-generation-struct anywhere I want and for example let a delegate present it or pass it around until I reach a UIViewController who can present it, if my caller isn't one.

Therefore in my very simple case, I'll go with:

enum MyAlertType {
    case a
    case b
}

struct MyAlert {
    static func showAlert(ofType type: MyAlertType, handler: ((UIAlertAction) -> ())? = nil) -> UIAlertController {

        var message: String
        switch type {
        case .a:
            message = "A is a nice letter!"
        case .b:
            message = "B is a nice letter!"
        }

        let alert = UIAlertController(title: "Do you know which letter is nice?", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))

        return alert
    }
}

Thanks to everybody participating in dissolving the blockade in my head.

1
  • Since a view controller is required anyway to present the alert controller the protocol extension might be the most suitable solution.
    – vadian
    May 18, 2017 at 9:11

3 Answers 3

7

Making static function is common and convenient approach. Please, pay attention that type you created is only for namespacing.

Alec O's answer is nice, but sometimes you want to pass some action you want to perform when you press OK button. Also I would pick struct instead of class.

Here is my version of making alert:

struct Alert {
static func errorAlert(title: String, message: String?, cancelButton: Bool = false, completion: (() -> Void)? = nil) -> UIAlertController {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let actionOK = UIAlertAction(title: "OK", style: .default) {
        _ in
        guard let completion = completion else { return }
        completion()
    }
    alert.addAction(actionOK)

    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    if cancelButton { alert.addAction(cancel) }

    return alert
}

And usage in ViewController's subclass:

    // Creating alerts:
    let simpleAlert = Alert.errorAlert(title: "Error", message: "Simple message")
    let alertWithCompletionAndCancel = Alert.errorAlert(title: "Message", message: "Message", cancelButton: true) { 
        // do something awesome
    }

    // Presenting alerts:
    present(simpleAlert, animated: true)
    present(alertWithCompletionAndCancel, animated: true)
1
  • I definitely agree about the struct!
    – Alec O
    May 18, 2017 at 11:27
0

I would suggest returning the alert from the function for the view controller to show. The custom alert class should not be presenting anything, if your aim is to use best practices.

class MyAlert {
    static func generateAlert(ofType type: MyAlertType) -> UIAlertController {

        var message: String
        switch type {
        case .a:
            message = "A is a nice letter!"
        case .b:
            message = "B is a nice letter!"
        }

        let alert = UIAlertController(title: "Do you know which letter is nice?", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))
        return alert
    }
}

This will be the code that you repeat throughout the application. If multiple alerts are used in one view controller then you can initialized MyAlert globally for that view controller.

let myAlert = MyAlert()
let alert = myAlert.generateAlert(ofType: MyAlertType.a)
self.present(alert)
2
  • Shouldn't in this case generateAlert func be a instance func instead of a static one or instead call MyAlert.generateAlert(ofType:)?
    – xxtesaxx
    May 17, 2017 at 17:12
  • Definitely! I didn't go that far, as I was taking the code that was already there and making adjustments
    – Alec O
    May 17, 2017 at 17:14
0

![This is the way I did
]
1

When I want to present an alert, I did this:

let alertControl = AlertController.shared.alert(alertTitle: "Error Login", msg: "Please provide your email and password to login", style: .cancel, titleForAlertBtn: "OK")  
present(alertControl, animated: true, completion: nil)
3
  • Thanks but I was not asking how you did it but rather to explain why one approach is better than the other and what the best practices are. Also from your code it looks like you might want to use "static let shared = AlertController()" as the singleton pattern since it does not look like you are going to change it ever, do you?. :)
    – xxtesaxx
    May 17, 2017 at 17:26
  • Also, why are you creating a Singleton in this case at all? Wouldn't a static function be more efficient since you could safe the cost of instantiation of an object completely or am I missing something which you don't show in the picture? I don't see any calls to self in there and therefore you'd probably be fine without a class. This is similar to my mentioned approach with a enum/struct/class with a static function.
    – xxtesaxx
    May 17, 2017 at 17:27
  • It would be nice if you could've copy+pasted the code instead of posting a link to a picture
    – Alec O
    May 18, 2017 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.