Reputation: 11607
One of my Swift code block is an alert popup:
func alertNewBillCreated() {
let alert = UIAlertController(title: "Success", message: "Bill created and ready to be paid", preferredStyle: UIAlertControllerStyle.Alert)
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (UIAlertAction) in
self.navigationController?.popViewControllerAnimated(true)
}
alert.addAction(actionOK)
self.presentViewController(alert, animated: true, completion: nil)
}
Reading other SO posts like this: Writing handler for UIAlertAction
They all gave examples where the handler part is inclusive and explicitly defined, e.g.:
UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: {(alert: UIAlertAction!) in println("Foo")
However, in my above code which I used Xcode's autocomplete to help me write the alert block, my version doesn't have the comma followed the handler
key.
These two variations also works (in addition to my first block of code above):
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) in
...
})
and
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) in
...
})
What is this odd Swift syntax exception rule ?
Isn't this a bug ?
Do we not separate function parameters with commas ?
It looks to me like I'm calling a function UIAlertAction()
and only passing it two parameters - title
and style
since there are only 2 commas:
UIAlertAction(__ , __ ) { ... }
Or is...this...the Swift equivalent of Ruby blocks? (Best explanation of Ruby blocks?)
My alert code works, it's not broken, in case anyone is curious.
Seems a bit inconsistent with so many rules and odd syntax, making it hard/harder to remember the rules for Swift syntax and learning Swift.
Hopefully by Swift 4.0, all these things are ironed out...
Maybe I'm complaining too much :D
Upvotes: 0
Views: 148
Reputation: 804
If the last parameter is a block it can be appended like a method body.
Read more.
Upvotes: 1