简体   繁体   English

Swift功能参数默认值

[英]Swift Function Parameter Default Value

I am creating a wrapper function for presenting an alert view in swift. 我正在创建一个包装器功能,以快速呈现警报视图。

Here is the current working code but currently I don't have it available to pass a function for the "completion" parameter in the .presentViewController function 这是当前的工作代码,但是目前我无法在.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)
}

I want to be able to pass a function to showAlert and have that function be called under completion, but I want that parameter to be optional, so by default it is 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)
}

I get the following, cannot convert value of type '()' to expected argument type '() -> Void?' 我得到以下信息,无法将类型'()'的值转换为预期的参数类型'()->空吗​​?'

EDIT 编辑

Thanks to Rob, it now runs syntactically but when I try to call it, I get: 感谢Rob,它现在可以在语法上运行,但是当我尝试调用它时,我得到:

cannot convert value of type '()' to expected argument type '(() -> Void)?' 无法将类型'()'的值转换为预期的参数类型'(()-> Void)?

Here is how I'm calling it 这是我的称呼方式

showAlert(self, title: "Time", message: "10 Seconds", action: test())

test() {
    print("Hello")

} }

You placed the question mark in the wrong place. 您将问号放在错误的位置。 This works: 这有效:

// wrong: action: (() -> Void?) = nil
// right: action: (() -> Void)? = nil

func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void)? = nil)
{
    ...
}

And don't include the brackets when you call it: 并且在调用时不要包括方括号:

showAlert(self, title: "Time", message: "10 Seconds", action: test)

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

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