Add integer values present in an array of custom objects

喜你入骨 提交于 2019-12-02 23:35:36

问题


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]()

回答1:


This can be done with reduce in a one-liner:

let sum = offerings.reduce(0, { $0 + $1.amount })

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

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.

You can also read the reduce documentation for more details.



来源:https://stackoverflow.com/questions/52048523/add-integer-values-present-in-an-array-of-custom-objects

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