2017-03-13 156 views
2

我有一個實用程序類,其中包含多個其他類使用的函數。其中之一是一個報警功能:默認情況下使用調用對象的「self」的方法

class Utils { 
    func doAlert (title: String, message: String, target: UIViewController) { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) 
     target.present(alert, animated: true, completion: nil) 
    } 
} 

此功能將始終瞄準視圖控制器上self,所以我想不用我每次調用該函數時添加target: self,但我不能只將其設置爲默認值,因爲這會導致它回到Utils類。有什麼方法可以重寫這個以避免這種情況?

回答

4

實用程序類是這個原因的反模式完全是,你真的想使用什麼是extension

extension UIViewController { 
    func doAlert(title: String, message: String) { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) 
     self.present(alert, animated: true, completion: nil) 
    } 
} 

,然後就可以直接調用該方法上所有的控制器:

self.doAlert(title: "title", message: "message") 

通常避免使用實用方法的類。嘗試將方法添加到功能實際所屬的類型中。

2

而不是把功能在你的Utils類的,你可以把它放在一個擴展的UIViewController,像這樣:

extension UIViewController { 
     func doAlert (title: String, message: String) { 
      let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) 
      alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) 
      target.present(alert, animated: true, completion: nil) 
     } 
相關問題