[ACCEPTED]-Swift 3 - Reduce a collection of objects by an Int property-reduce
Accepted answer
var total = arr.reduce(0, {$0 + $1.distance!})
The first argument is the accumulator, it 3 is already an integer.
Note that this will 2 crash on elements without distance. You 1 could fix that e.g. using:
let total = arr.reduce(0, {$0 + ($1.distance ?? 0)})
or
let total = arr.compactMap { $0.distance }.reduce(0, +)
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.