Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values of properties inside array of custom objects using reduce

Tags:

swift

I have following model

class Foo {
var value: Double
var color: UIColor

init?(value: Double, color: UIColor) {
    self.value = value
    self.color = color
  }
}

How can I sum all value property inside of [Foo] using reduce?

like image 637
Alexey K Avatar asked May 11 '17 09:05

Alexey K


2 Answers

It simply like this

let sum = array.reduce(0) { $0 + $1.value }
like image 84
Nirav D Avatar answered Sep 17 '22 07:09

Nirav D


The same way as with plain numbers:

let foos: [Foo] = ...
let sum = foos.lazy.map { $0.value }.reduce(0, +)
like image 43
Sulthan Avatar answered Sep 19 '22 07:09

Sulthan