Swift 3 - 通过 Int 属性 减少对象集合

Swift 3 - Reduce a collection of objects by an Int property

我有一个包含 3 个对象的数组,如下所示:

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]

当我减少数组并将其分配给一个变量时,我只能对数组中的最后一个元素求和。

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

如果我尝试 $0.distance!它错误 "expression is ambiguous without more context".

我试着说得更明确一点:

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

但是这个错误与“'Int' 与上下文类型‘_’不兼容” 我如何将它减少到距离总和?

var total = arr.reduce(0, {[=10=] + .distance!})

第一个参数是累加器,它已经是一个整数。

请注意,这会在没有距离的元素上崩溃。你可以解决这个问题,例如使用:

let total = arr.reduce(0, {[=11=] + (.distance ?? 0)})

let total = arr.compactMap { [=12=].distance }.reduce(0, +)