Add integer values present in an array of custom o

2020-05-09 23:08发布

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条回答
▲ chillily
2楼-- · 2020-05-09 23:35

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.

查看更多
登录 后发表回答