我正在尝试将可为空的完成块添加到自定义函数
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)
}
})
完成块始终为零。
答案 0 :(得分:2)
以下是定义无法完成的方法
func function(completion: (Void -> Void)? = nil) {
completion?()
}
您可以通过几种不同的方式将其称为
function() //without any argument
function({ //with parens and braces
print("I will get called")
})
function() { //with parens and braces
print("I will get called")
}
function { //without parens
print("I will get called")
}
答案 1 :(得分:1)
编辑:仅使用Swift 2.0进行测试..
您应该更改完成参数。
示例:
func Test( completion: () -> () = {_ in }) {
completion()
}
可以通过两种不同的方式调用此函数:
Test() // Nothing happens
Test({ print("Completed") }) // Prints Completed
希望这会有所帮助:)
答案 2 :(得分:0)
这对我有用
typealias CompletionHandler = (_ success:Bool) -> Void
func yourCompletionBlockName(completionHandler: CompletionHandler) {
//code
let flag = true
completionHandler(flag)
}
在需要时呼叫完成阻止
yourCompletionBlockName(completionHandler: { (success) -> Void in
if success {
} else {
}
})