Care and Feeding of Closures
We’re going to see closures in several more places in the iOS SDK, so it’s a good idea to make sure we’re fully comfortable with them before we move on.
Trailing Closure Syntax
One little change we can make right off the bat will make our code easier to read. In Swift, if the last argument to a method or function is a closure, we can omit its label and put it directly after the closing parenthesis of the declaration. In other words, if we start with this:
| function(param1: foo, param2: { bar in |
| ... |
| }) |
We can instead write:
| function(param1: foo) { bar in |
| ... |
| } |
This is much easier to read and eliminates the weird trailing }) when the closure and parameter list end. We’ll use this syntax from here on out.
Get iOS 10 SDK Development, 1st Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.