繁体   English   中英

Swift功能参数默认值

[英]Swift Function Parameter Default Value

我正在创建一个包装器功能,以快速呈现警报视图。

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

我得到以下信息,无法将类型'()'的值转换为预期的参数类型'()->空吗​​?'

编辑

感谢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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM