Alexey K
Alexey K

Reputation: 6723

Sum values of properties inside array of custom objects using reduce

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?

Upvotes: 14

Views: 8117

Answers (2)

Sulthan
Sulthan

Reputation: 130102

The same way as with plain numbers:

let foos: [Foo] = ...
let sum = foos.lazy.map { $0.value }.reduce(0, +)

Upvotes: 9

Nirav D
Nirav D

Reputation: 72410

It simply like this

let sum = array.reduce(0) { $0 + $1.value }

Upvotes: 54

Related Questions