Reputation: 6384
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.
Upvotes: 0
Views: 73
Reputation: 285230
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)
}
}
Upvotes: 1