Reputation: 171
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")
}
Upvotes: 2
Views: 1161
Reputation: 93181
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)
Upvotes: 3