Today, I’ll present one of my favorite syntactic sugars in swift:

var value = array.reduce(0) {
    $0 + Int($1.rect.height)
}

While trying to sum the result of all the rectangles in an array, I decided to use functional programming. I recalled watching the $ shorthand somewhere, so I decided to give it a try, and Voàla. Can’t get better than this.

Let’s write the previous code in the verbose form, and break it down:

var value = array.reduce(0, {
        (total, current) in 
        return total + Int(current.rect.height) 
}) 

So… There are three important shortcuts:

  1. We add the closure outside the method call
  2. We get rid of the parameter declaration, and use $n instead.
  3. We get rid of return