14

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?

2 Answers 2

54

It simply like this

let sum = array.reduce(0) { $0 + $1.value }
Sign up to request clarification or add additional context in comments.

Comments

9

The same way as with plain numbers:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.