0

I have a struct that handles alerts for me. It just has one function:

func presentAlert(_ title:String, _ message:String, _ presenter:ViewController) {

        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        myAlert.addAction(okAction)
        presenter.present(myAlert, animated:true, completion:nil)
    }

I can call this fine from the viewcontroller. But on a subclass, AddTopicViewController I am getting an error:

myController.alert.presentAlert("Form errors", strErrMsg, self)

//error from compiler
Cannot convert value of type 'AddTopicViewController' to expected argument type 'ViewController'

So, two questions:

Since AddTopicVC is a subclass of VC I thought it would pass through for something requiring a VC. Obviously wrong on that one. Could someone explain the flaw in my logic on that?

Any suggestions on how to accomplish my goal? The app has a lot of validation and alerts are presented whenever the user hasn't entered required data, but all the viewcontrollers are subclass. I tried extending viewcontroller with the function but the subclasses gave an error that the method wasn't available.

Thanks for the help.

2
  • 1
    Where is defined AddTopicViewController? I'd tend to say/guess that's it's inherited from UIViewController, not ViewController. Commented Nov 2, 2017 at 16:14
  • Yeah, that was my error. Commented Nov 2, 2017 at 16:19

1 Answer 1

1

The easiest way is to use the presumed base class, UIViewController, which all view controllers inherit from.

func presentAlert(_ title:String, _ message:String, _ presenter:UIViewController)

Alternatively use an extension of UIViewController

extension UIViewController {

    func presentAlert(_ title:String, _ message:String) {

        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        myAlert.addAction(okAction)
        present(myAlert, animated:true, completion:nil)
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I see where I fell off the rails. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.