2016-09-10 59 views
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()”,然后继续执行任何我想以后的事情。

有什么办法可以做到吗?或者我的逻辑违背了什么协议是为了设计而且不会发生?

回答

3

有一个简单的解决方案:只需在扩展中添加一个defaultShow方法即可。

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() 
    } 
} 

因此,在你的代码,你可以叫defaultShow

extension ViewController: ShowAlert { 
    // ... 

    func show() { 
     self.defaultShow() 
     print("Good day sir!") 
    } 
} 

也有另一种解决方案,你可以叫.show()而不是.defaultShow()。然而它使用铸造和破坏封装。如果你想看到它,让我知道。

+0

好主意,但我在想Swift有些东西可以处理这种情况,而不需要添加新的功能。不管怎么说,还是要谢谢你。 – RodolfoAntonici