繁体   English   中英

IOS swift中的完成块

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM