Swift 3 - Decrease Collection of Objects by Int Object

I have an array containing 3 objects:

class AClass {
    var distance: Int?
}

let obj0 = AClass()
obj0.distance = 0

let obj1 = AClass()
obj1.distance = 1

let obj2 = AClass()
obj2.distance = 2

let arr = [obj0, obj1, obj2]

      

When I decrease the array and assign it to a variable, I can only sum the last element in the array.

let total = arr.reduce(0, {$1.distance! + $1.distance!})  //returns 4

      

If I try $ 0.distance! these are errors with "expression is ambiguous without additional context".

I tried to be more explicit:

var total = arr.reduce(0, {(first: AClass, second: AClass) -> Int in
    return first.distance! + second.distance!
})

      

But these errors with "Int" are incompatible with the contextual type "_" "How to reduce it to the sum of the distances?

+3


source to share


1 answer


var total = arr.reduce(0, {$0 + $1.distance!})

      

The first argument is the accumulator, it is already an integer.

Note that this will crash on elements with no distance. You can fix this for example. through:



let total = arr.reduce(0, {$0 + ($1.distance ?? 0)})

      

or

let total = arr.flatMap { $0.distance }.reduce(0, +)

      

+9


source







All Articles