iOSGeek - 8 months ago 39

iOS Question

I have an array which contains an arrays of double, like in the screenshot:

My goal is to get the sum of the multiplication of the double elements of each array. It means, I want to multiply all elements of each array then in my case I will have 3 values so I get the sum of them.

I want to use

`reduce`

`flatMap`

What I have tried ?

`totalCombinations.reduce(0.0) { $0 + ($1[0]*$1[1]*$1[2]) }`

but this work only when I know the size of the arrays that contains the doubles.

Answer

Just another way

```
let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
let sum = lists.reduce(0) { $0 + $1.reduce(1, combine: *) }
```

If you define this extension

```
extension SequenceType where Generator.Element == Double {
var product : Double { return reduce(1.0, combine: *) }
}
```

then you can write

```
let sum = lists.reduce(0) { $0 + $1.product }
```

With the extension defined above you can also write

```
let sum = lists.map { $0.product }.reduce(0, combine:+)
```