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

时间:2018-08-08 21:11:42

标签: ios arrays swift dictionary struct

我有一系列称为“报价”的产品。我对数组进行了分组,如下所示。

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"]

我想对各个公司的所有金额进行汇总。请帮助我达到这个结果。

2 个答案:

答案 0 :(得分:1)

似乎您需要找到所有分组数组的总和,可以为此使用mapValues

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

amounts将是一个具有与groupedBonds(在这种情况下为公司名称)相同的键,但是具有转换闭包的结果作为值的字典,该闭包可以同时计算或不计算。每个数组的总和。

答案 1 :(得分:1)

假设要提供的数据等于

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
]