Swift 3 - 通过 Int 属性减少对象集合 [英] Swift 3 - Reduce a collection of objects by an Int property

查看:38
本文介绍了Swift 3 - 通过 Int 属性减少对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我尝试 $0.distance!它的错误是表达式不明确,没有更多上下文".

If I try $0.distance! it errors with "expression is ambiguous without more context".

我尝试更明确:

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

但是这个带有'Int'的错误与上下文类型'_'不兼容"如何将其减少到距离的总和?

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

推荐答案

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)})

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

这篇关于Swift 3 - 通过 Int 属性减少对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆