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]()
This can be done with
reduce
in a one-liner:$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: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 thenextPartialResult
(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.