【发布时间】:2015-11-10 09:47:17
【问题描述】:
我正在尝试向自定义函数添加一个可为空的完成块
func disPlayAlertMessage(titleMessage:String, alertMsg:String, completion: (() -> Void)? = nil){
AlertMessage.alertMessageController = UIAlertController(title: titleMessage, message:
alertMsg, preferredStyle: UIAlertControllerStyle.Alert)
AlertMessage.alertMessageController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
if completion == nil {
controller.presentViewController(AlertMessage.alertMessageController, animated: true, completion: nil)
} else {
controller.presentViewController(AlertMessage.alertMessageController, animated: true, completion: {
completion!()
})
}
return
}
当我尝试像下面这样调用上述函数时
AlertMessage(controller: self).disPlayAlertMessage(CustomAlertMessages.AlertTitle, alertMsg: CustomAlertMessages.DOANoUpdate, completion: { () -> Void in
{
self.navigationController?.popViewControllerAnimated(true)
}
})
完成块始终为零。
【问题讨论】:
-
可以在 controller.presentViewController 之前添加 print-s 吗?确保该值真的为零,并且控制器没有调用它的问题
-
当我运行它时它会进入 nil 部分,所以显然完成是 nil
-
您是否设置了断点,或者您假设这是因为未调用完成?
-
我也试过断点
-
该方法似乎正确,还有一些其他问题。我复制了你的代码并添加到了一个操场上,它正在工作:
func disPlayAlertMessage(titleMessage:String, alertMsg:String, completion: (() -> Void)? = nil){ print (titleMessage + alertMsg); completion!() } disPlayAlertMessage("Midhun", alertMsg: "MP") { () -> Void in print("Yes Working") }