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

北城以北 提交于 2019-12-07 07:38:46

问题


I have an array containing 3 objects like so:

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 reduce 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! it errors with "expression is ambiguous without more context".

I tried being more explicit:

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

But this errors with "'Int' is incompatible with contextual type '_'" How do I reduce it to the sum of the distances?


回答1:


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 without distance. You could fix that e.g. using:

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

or

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


来源:https://stackoverflow.com/questions/44358438/swift-3-reduce-a-collection-of-objects-by-an-int-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!