1
我有这个简单的类和一个名为'ShowAlert'的假设协议,它是默认实现和默认ViewController以及它的ShowAlert协议实现的扩展。Swift覆盖协议扩展保持扩展行为
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!")
}
}
这就像在一个子类,在那里我可以称之为“super.show()”,然后继续执行任何我想以后的事情。
有什么办法可以做到吗?或者我的逻辑违背了什么协议是为了设计而且不会发生?
好主意,但我在想Swift有些东西可以处理这种情况,而不需要添加新的功能。不管怎么说,还是要谢谢你。 – RodolfoAntonici