添加自定义对象数组中存在的整数值 [英] Add integer values present in an array of custom objects
问题描述
我有一个称为Offer的结构,如下所示.我需要使用reduce和/或map添加报价"提供的数组中存在的所有金额.请帮助我.
I have a struct called Offering as shown below. I need to add all the amount present in the array of Offering "offerings" using reduce and/or map. Please help me.
public struct Offering: Codable {
public let company: String
public let amount: Int
public let location: String
}
var offerings = [Offering]()
推荐答案
这可以通过reduce
在单层中完成:
This can be done with reduce
in a one-liner:
let sum = offerings.reduce(0, { $0 + $1.amount })
$0
表示部分结果(即到目前为止已累积的结果),而$1
是Array中的当前元素.上面的充实版本看起来像:
$0
represents the partial result (i.e., what's been accumulated so far) and $1
is the current element in the Array. A fleshed-out version of the above would look like:
let sum: Int = offerings.reduce(0, { (sum: Int, element: Offering) -> Int in
return sum + element.amount
})
本质上,闭包是在数组中的每个元素上调用的.您的累加器"值最初设置为您传递的第一个参数(initialResult
;在本例中为0
),然后作为第一个参数公开给您传递的闭包.闭包还接收数组中的下一个元素作为第二个参数,闭包的返回值是nextPartialResult
(即随后将累加器"设置为的值).该闭包将与数组的每个元素一起调用,部分结果每次都会更新,并传递到下一个调用.
Essentially, the closure is called on each element in the array. Your "accumulator" value is initially set to the first parameter you pass (initialResult
; in this case, 0
) and is then exposed as the first parameter to the closure you pass. The closure also receives the next element in the array as the second parameter, and the return value of the closure is the nextPartialResult
(i.e., the value to which the "accumulator" is then set). The closure is called with each element of the array, with the partial result being updated each time and passed through to the next call.
您还可以阅读 reduce
文档以了解更多信息详细信息.
You can also read the reduce
documentation for more details.
这篇关于添加自定义对象数组中存在的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!