gpt4 book ai didi

ios - 如何使闭包作为函数参数可选

转载 作者:行者123 更新时间:2023-11-30 14:07:22 26 4
gpt4 key购买 nike

我有一个助手来显示 AlertView:

func showAlertBoxOK(headline:String, message:String, OkButtonText:String, viewController:UIViewController, completionOK:() -> Void){

let alertController = UIAlertController(title: headline, message: message, preferredStyle:UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: OkButtonText, style: UIAlertActionStyle.Default)
{ action -> Void in
if completionOK() != nil {
completionOK()
}
})
viewController.presentViewController(alertController, animated: true, completion: nil)
}

现在我想让参数completionOK可选。我试过了完成OK:() -> 无效? = nil` 但他给了我一个编译器错误。我的调用应该像这样不带参数:

showAlertBoxOK("Could not retrieve position", "Edit iOS Settings - GeoLocation denied. Sorry. Please fix that und restart App.", "OK", self)

参数如下:

showAlertBoxOK("Could not retrieve position", "Edit iOS Settings - GeoLocation denied. Sorry. Please fix that und restart App.", "OK", self, { println("hello world") })

有什么帮助吗?

最佳答案

您可以使用不同的方法并使用默认值定义参数,如下所示:

func showAlertBoxOK(headline:String, message:String, OkButtonText:String, viewController:UIViewController, completionOK:() -> Void = {}){

let alertController = UIAlertController(title: headline, message: message, preferredStyle:UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: OkButtonText, style: UIAlertActionStyle.Default)
{ action -> Void in
completionOK()
})
viewController.presentViewController(alertController, animated: true, completion: nil)
}

这样就可以用两种不同的方式调用函数,同时也简化了函数的定义。

关于ios - 如何使闭包作为函数参数可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32198276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com