简体   繁体   English

根据键快速添加分组字典元素的值

[英]Add values of grouped dictionary elements based on keys swift

I have an array of Offering called "offerings". 我有一系列称为“报价”的产品。 I have grouped the array as shown below. 我对数组进行了分组,如下所示。

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
}

The keys of the dictionary are the companies -> ["ABCD", "EFGH", "IJKL", "MNOP"] 词典的关键字是companies -> ["ABCD", "EFGH", "IJKL", "MNOP"]

I want to sum all the amounts of the respective companies. 我想对各个公司的所有金额进行汇总。 Please help me in achieving this result. 请帮助我达到这个结果。

Seems you need to find the sum for all grouped arrays, you can use mapValues for this: 似乎您需要找到所有分组数组的总和,可以为此使用mapValues

let amounts = groupedBonds.mapValues { $0.reduce(0) { $0 + $1.amount} }

amounts will be a dictionary having the same keys as groupedBonds (the company name in this case), but having as values the result of the transformation closure, which, coincidently or not, computes the sum for every array. amounts将是具有字典中的相同的密钥groupedBonds (公司名在这种情况下),但具有与值变换闭合,其中,一致地或不,计算用于每个阵列的总和的结果。

assuming what data.offerings equals to 假设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"),
]

I want to sum all the amounts of the respective companies. 我想对各个公司的所有金额进行汇总。

  let sumAmountByComany = offerings.reduce(into: [:]) { (result, offer)  in
         result[offer.company] = (result[offer.company] ?? 0 ) + offer.amount
    }

result 结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM