swift - 错误无法将类型 `Void` 的值转换为预期的参数类型 `() -> Void` UIAlertController

标签 swift uialertcontroller

我经常需要向用户显示警告,我发现自己一遍又一遍地编写相同的代码,所以我构建了一个方便的方法。

当在 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/

相关文章:

ios9 - iOS 9 中的操作表问题

ios - 显示 UIAlert 会使应用程序崩溃吗?

ios - Swift SubView 在 tableView 前面

ios - 使用自定义委托(delegate)从 NSURLSessionUploadTask 获取服务器响应

swift - 在 Swift 的自定义单元格中显示操作表

ios - UIAlertController 在 Swift 3.0 中使用辅助类

ios - UIActivityViewController 中 UILabel 的 UIAppearance

c++ - iOS 如何打印c++变量的NSLOG(二维 vector 数组)?

swift - 如何在swift中添加随机数值

swift - iOS swift : Install and Unistall views programmatically