我经常要向用户显示警告,我发现自己一遍又一遍地编写相同的代码,所以我构建了一种方便的方法。
在self.convenience.showAlertToUser()
中调用viewDidLoad
时,我收到参数doThisAction
的错误无法将类型Void
的值转换为预期的参数类型() -> Void
< / em>的。我不明白为什么,因为我传入了那种类型的论点。此外,我不知道我是否正在创建保留周期,所以我将非常感谢您的帮助。
class ConvenienceMethods {
func showAlertToUser(alertMessage: String = "",actionOkTitle:String, actionCancelTitle:String, controller: UIViewController, cancelAction: Bool, doAction: @escaping (() -> Void)) {
let customAlert = UIAlertController(title: "", message: alertMessage, preferredStyle: .alert)
let actionCancel = UIAlertAction(title: actionCancelTitle, style: .cancel, handler: nil)
let actionOk = UIAlertAction(title: actionOkTitle, style: .default, handler: { (action: UIAlertAction) in
doAction()
})
if cancelAction == true {
customAlert.addAction(actionCancel)
}
customAlert.addAction(actionOk)
controller.present(customAlert, animated: true, completion: nil)
}
}
class ManageFeedbackTableViewController {
let convenience = ConvenienceMethods()
override func viewDidLoad() {
super.viewDidLoad()
let doThisAction = self.segueWith(id: "segueID")
self.convenience.showAlertToUser(alertMessage: "someMessage", actionOkTitle: "OK", actionCancelTitle: "No", controller: self, cancelAction: false, doAction: doThisAction)
}
//perform an action
func segueWith(id: String) -> Void{
self.performSegue(withIdentifier: id, sender: self)
}
}
答案 0 :(得分:1)
因为您要传递对函数的引用,但结果本身。
替换
let doThisAction = self.segueWith(id: "segueID")
通过:
let doThisAction = { self.segueWith(id: "segueID") }
答案 1 :(得分:1)
@bibscy, doThisAction是一个闭包,我们可以在其中分配“{}”中的代码块,如下所示: - 让doThisAction = {self.segueWith(id:“segueID”)}这将起作用。