我经常需要向用户显示警告,我发现自己一遍又一遍地编写相同的代码,所以我构建了一个方便的方法。
当在 viewDidLoad
中调用 self.convenience.showAlertToUser()
时,我收到参数 doThisAction
的错误 无法转换类型的值Void
到预期的参数类型 () -> Void
。我不明白为什么,因为我传入了那种类型的参数。另外,我不知道我是否正在创建一个保留周期,所以非常感谢你的帮助。
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)
}
}
最佳答案
因为您要传递对函数的引用而不是结果本身。
替换
让 doThisAction = self.segueWith(id: "segueID")
作者:
让 doThisAction = { self.segueWith(id: "segueID") }
关于swift - 错误无法将类型 `Void` 的值转换为预期的参数类型 `() -> Void` UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49256822/