简体   繁体   中英

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

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

// 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:

cannot convert value of type '()' to expected argument type '(() -> 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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