我正在创建一个包装函数,用于在 swift 中呈现警报 View 。
这是当前的工作代码,但目前我无法为 .presentViewController 函数中的“completion”参数传递函数
func showAlert(viewClass: UIViewController, title: String, message: String)
{
// Just making things easy to read
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
// Notice the nil being passed to "completion", this is what I want to change
viewClass.presentViewController(alertController, animated: true, completion: nil)
}
我希望能够将函数传递给 showAlert 并在完成时调用该函数,但我希望该参数是可选的,因此默认情况下它为 nil
// Not working, but this is the idea
func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void?) = nil)
{
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
viewClass.presentViewController(alertController, animated: true, completion: action)
}
我得到以下信息,无法将类型“()”的值转换为预期参数类型“() -> Void?”
编辑
感谢 Rob,它现在可以按语法运行,但是当我尝试调用它时,我得到:
无法将类型“()”的值转换为预期的参数类型“(() -> Void)?”
这是我的称呼
showAlert(self, title: "Time", message: "10 Seconds", action: test())
test() {
print("Hello")
}
最佳答案
您把问号放在了错误的位置。这有效:
// wrong: action: (() -> Void?) = nil
// right: action: (() -> Void)? = nil
func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void)? = nil)
{
...
}
调用时不要包含括号:
showAlert(self, title: "Time", message: "10 Seconds", action: test)
关于ios - Swift 函数参数默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443112/