This writing is the result of a series of implicit declaration, thanks to the smart Swift compiler.
Let's look how we go from the most extensive form to the very short one.
Test it all in playground, to see it working.
The very long form is:
let sum = items.reduce(0, { (total:Int, value:Int) -> Int in total + value })
The closure may be moved after the ()
let sum = items.reduce(0) { (total:Int, value:Int) -> Int in total + value }
As type (Int) may be infered because array of Int, you can remove types declarations:
let sum = items.reduce(0) { (total, value) in total + value }
Now, we don't need parenthesis either:
let sum = items.reduce(0, { total, value in total + value })
or
let sum = items.reduce(0) { total, value in total + value }
We can also use shorthands to identyify parameters:
let sum = items.reduce(0, { $0 + $1 })
or
let sum = items.reduce(0) { $0 + $1 }
and finally, when closure is inside (), as arguments $0 and $1 can be deduced, we can just write the shortest form:
let sum = items.reduce(0, +)
Imagine now you want to sum the squares; the compact form does not work.
You should write at least:
let sumSquares = items.reduce(0) { $0 + $1*$1 }
But you could also first map the array to the squares, and use the compact reduce !
let sumSquares = items.map({$0*$0}).reduce(0, +)
Mastering those func map, reduce, filter and some other is really useful. You could read these tutorials:
h ttps://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/
h ttps://medium.com/@abhimuralidharan/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8