Reputation: 808
How would one go about accomplishing something like the following in a more elegant way in Swift 4 e.g using map and/or reduce.
I've simplified the code for the sake of posting here, but note it does require the use of an index.
var numbers = [50, 20, 70, 80, 90]
var result = [0,0,0]
for number in numbers {
for i in 0...2 {
result[i] += number + i
}
}
The end result should be:
[Int] = 3 values {
[0] = 310
[1] = 315
[2] = 320
}
Upvotes: 5
Views: 3736
Reputation: 763
This is equivalent
let result = (0...2).map({ index in numbers.reduce(0) { (sum, current) in sum + current + index } })
or this if you want to use result
array
let r = result.enumerated().map({ (index, _) in numbers.reduce(0) { (sum, current) in sum + current + index } })
but more efficient will be something like that
let sum = numbers.reduce(0, +)
let resultsExpected = 3
let result = (0..<resultsExpected).map({ $0 * numbers.count + sum })
Upvotes: 7