![](/img/trans.png)
[英]How to invoke completion block in CloudKit in Swift 2 in iOS 9?
[英]Completion block in IOS swift
我正在嘗試將一個可空的完成塊添加到自定義函數
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)
}
})
完成塊始終為零。
以下是定義無法完成的方法
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")
}
編輯:僅使用Swift 2.0測試..
您應該更改完成參數。
例:
func Test( completion: () -> () = {_ in }) {
completion()
}
可以通過兩種不同的方式調用此函數:
Test() // Nothing happens
Test({ print("Completed") }) // Prints Completed
希望這可以幫助 :)
這適合我
typealias CompletionHandler = (_ success:Bool) -> Void
func yourCompletionBlockName(completionHandler: CompletionHandler) {
//code
let flag = true
completionHandler(flag)
}
在需要時調用完成塊
yourCompletionBlockName(completionHandler: { (success) -> Void in
if success {
} else {
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.