Reputation: 1
Hi I just started learning Swift. I am just beginner to learn ios development.
func showOkay() {
let title = NSLocalizedString("a title", comment: "")
let message = NSLocalizedString("msg", comment: "")
let cansal = NSLocalizedString("cancel", comment: "")
let ok = NSLocalizedString("ok", comment: "")
let alertController = UIAlertController (title: title, message: message, preferredStyle: .alert)
let cancelAlertAction = UIAlertAction (title : cansal, style : .cancel) {
_ in print("cancel") // i don't understand this line . its just a print or somthing else. why i cant use print here.
}
let okAction = UIAlertAction(title: ok , style : .default) {
_ in print("ok") // i don't understand this line. its just a print or somthing else. why i cant use print here.
}
alertController.addAction(cancelAlertAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
@IBAction func btnAction(_ sender: Any) {
showOkay()
}
If I use print()
only they give me errror like
Cannot convert value of type '() -> ()' to expected argument type '((UIAlertAction) -> Void)?'
Upvotes: 0
Views: 163
Reputation: 154583
This statement is using trailing closure syntax. The stuff between {
and }
is actually a closure that is passed to UIAlertAction
to be called later when the event happens. When the closure is called, it will be passed the UIAlertAction
object that was created.
let cancelAlertAction = UIAlertAction (title : cansal , style : .cancel) {
_ in print("cancel") \\ i don't understand this line . its just a print or somthing else . why i cant use print here.
}
If you intend not to use the alert action, then you need the _ in
to tell Swift that you are ignoring the UIAlertAction
and doing nothing with it. You are saying, I know there is a parameter but I am ignoring it.
If you don't specify the _ in
, Swift infers your closure type to be of type () -> ()
which means it takes nothing and produces nothing. This doesn't match the type of the closure you are expected to provide which is (UIAlertAction) -> Void
(takes a UIAlertAction
and returns nothing).
It is usually written like this:
let cancelAlertAction = UIAlertAction (title : cansal , style : .cancel) { _ in
print("cancel")
}
which makes it clearer that the _ in
is the closure parameter syntax and not directly related to the print
statement.
Upvotes: 2