())? = nil, onAnotherAction:((a-6ren">
gpt4 book ai didi

swift - 将 "function with parameter"作为参数传递

转载 作者:行者123 更新时间:2023-11-28 13:55:28 27 4
gpt4 key购买 nike

这不编译

func showAlert(_ title: String, message: String, 
onOk: (()->())? = nil,
onAnotherAction:((anotherActionTitle : String)-> Void)? = nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)

let ok = UIAlertAction(title: "OK", style: .default) { (action) in
onOk?()
}

let anotherAction = UIAlertAction(title: anotherActionTitle, style: .default) { (action) in
onAnotherAction?()
}

alertController.addAction(ok)
alertController.addAction(anotherAction)

...
}

这个编译

func showAlert(_ title: String, message: String,
onOk: (()->())? = nil,
onAnotherAction:((String)-> Void)? = nil)

但是,我必须为 onAnotherAction() 的标题 anotherActionTitle 声明另一个参数。

有没有办法使第一种方法起作用?谢谢!

最佳答案

However, I have to declare another parameter for the title anotherActionTitle of onAnotherAction()

不,您不必那样做。只需将其作为整个函数的常规参数即可:

func showAlert(_ title: String, message: String,
onOk: (()->())? = nil,
anotherActionTitle: String? = nil,
onAnotherAction: (()->())? = nil) {

然后您的函数的其余部分将编译并正常工作。

关于swift - 将 "function with parameter"作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53936743/

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