Swift函数参数默认值

Swift Function Parameter Default Value

我正在创建一个包装函数,用于在 swift 中显示警报视图。

这是当前的工作代码,但目前我无法为 .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)