I am new to this escape function in Swift, but I follow a tutorial and I use the following function below: (the function is working for me)
static func showThreeOptions(messageText: String, titleOne:String, titleTwo: String, actionOne: @escaping () -> (Void), actionTwo: @escaping () -> (), currentView: UIViewController ) {
// create the alert
let alert = UIAlertController(title: "Alerta", message: messageText, preferredStyle: UIAlertController.Style.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: titleOne, style: UIAlertAction.Style.default, handler: { (alert) in
actionOne()
} ))
alert.addAction(UIAlertAction(title: titleTwo, style: UIAlertAction.Style.default, handler: { (alert) in
actionTwo()
} ))
alert.addAction(UIAlertAction(title: "Cancelar", style: UIAlertAction.Style.destructive, handler: nil))
// show the alert
currentView.present(alert, animated: true, completion: nil)
}
Now, I want to change the actionTwo() to actionTwo(number:Int),
but I don’t know how to change the signature actionTwo: @escaping () -> ()
How can I change the signature
actionTwo: @escaping () -> () to allow to be able to call actionTwo(number:Int) ?
—–UPDATE—–
I create the function
actionTwo(2) and it works. Thank you @RobNapier
But there is another problem now.
I call the function
AlertActions.showThreeOptions(
messageText: "Resenha Finalizada.",
titleOne: "Marcas/Fotos",
titleTwo: "Editar",
actionOne: self.someHandlerOne,
actionTwo: self.someHandlerTwo(2),
currentView: self
)
This is the functions
func someHandlerOne() {
print("test")
}
func someHandlerTwo(_ id:Int) {
print("test2")
}
Now I get the following error when I call someHandlerTwo(_ id:Int)
Cannot convert value of type ‘()’ to expected argument type ‘(Int) -> ()’
How can I fix that error?
—–UPDATE 2—–
I find out how to use a escaping function now
func notImplemented(resDado_id: Int) -> () {
print(resDado_id)
}
2
Answers
Change
@escaping () -> ()
to@escaping (Int) -> ()
. Instead of something that takes no parameters, you want something that takes one.It’s a little nicer to use Void for return values that are (), like
(Int) -> Void
, but it means the same thing.My suggestion is a different approach:
Write an extension of
UIViewController
and use theUIAlertAction
handler signature foractionOne
andactionTwo
.This is still more versatile and the
UIAlertAction
handler closures don’t escapeThe closures can even be declared as functions for example
Edit:
You don’t need to pass a parameter, you can create the handler inline and capture the
id