Ios Swift函数参数默认值

Ios Swift函数参数默认值,ios,swift,function,parameters,swift2,Ios,Swift,Function,Parameters,Swift2,我正在创建一个包装函数,用于在swift中显示警报视图 这是当前的工作代码,但目前我无法在.presentViewController函数中为“completion”参数传递函数 func showAlert(viewClass: UIViewController, title: String, message: String) { // Just making things easy to read let alertController = UIAlertController

我正在创建一个包装函数,用于在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)

如果不将其设置为可选,则不能将其设置为
nil
位于错误的位置,例如,它应该是
(()->Void)?=无
刚刚编辑了我的问题。你是对的,是吗?关但现在有问题称之为更正编辑,它是
showart(self,title:“Time”,message:“10秒”,action:{print(“Hello”)}
。或
showarter(self,title:“Time”,message:“10秒”){print(“Hello”)}
。谢谢!函数调用后的()是问题所在
test()
表示“执行函数
test
”<代码>测试单独指的是“名为
测试
的函数”