我有一系列的供品叫做“供品”。我已将数组分组,如下所示。

let groupedBonds = Dictionary(grouping: data.offerings) { (Offering) -> String in
            return Offering.company
        }

public struct Offering: Codable {
    public let company: String
    public let amount: Int
    public let location: String
}

字典的键是companies -> ["ABCD", "EFGH", "IJKL", "MNOP"]
我想把各公司的所有金额加起来。请帮助我取得这个结果。

最佳答案

假设data.offerings等于

let offerings = [
    Offering(company: "A", amount: 7, location: "a"),
    Offering(company: "A", amount: 4, location: "a"),
    Offering(company: "B", amount: 2, location: "a"),
    Offering(company: "C", amount: 3, location: "a"),
]

我想把各公司的所有金额加起来。
  let sumAmountByComany = offerings.reduce(into: [:]) { (result, offer)  in
         result[offer.company] = (result[offer.company] ?? 0 ) + offer.amount
    }

结果
[
 "C": 3,
 "B": 2,
 "A": 11
]

07-26 03:55