I have this simple class and an hypothetical protocol called 'ShowAlert', it's extension to do the default implementation and a default ViewController and it's ShowAlert protocol implementation.
protocol ShowAlert {
var titleForAlert: String! { get }
func messageForAlert() -> String!
func show()
}
extension ShowAlert where Self: UIViewController {
func show(){
let alert = UIAlertController(title: self.titleForAlert, message: self.messageForAlert(), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showItNow(sender: AnyObject) {
self.show()
}
}
extension ViewController: ShowAlert {
var titleForAlert: String! {
get{
return "Foo"
}
}
func messageForAlert() -> String! {
return "Bar"
}
func show() {
// here I want to call the default implementation of the protocol to show the alert, then do something else
print("Good day sir!")
}
}
It's like on a subclass where I could call a 'super.show()' and then continue implementing whatever I want to do after that.
There's any way to do it? Or my logic go against what protocols are design for and that don't suppose to happen?
There is a simple solution: Just add a defaultShow
method to the extension.
extension ShowAlert where Self: UIViewController {
func defaultShow(){
let alert = UIAlertController(title: self.titleForAlert, message: self.messageForAlert(), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func show() {
defaultShow()
}
}
So in your code you can just call defaultShow
:
extension ViewController: ShowAlert {
// ...
func show() {
self.defaultShow()
print("Good day sir!")
}
}
There is also another solution where you can call .show()
instead of .defaultShow()
. However it uses casting and breaks encapsulation. If you want to see it let me know.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments