首页 > 解决方案 > 快速添加基于键的分组字典元素的值

问题描述

我有一系列名为“产品”的产品。我已将数组分组,如下所示。

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

我想总结各个公司的所有金额。请帮助我实现这个结果。

标签: iosarraysswiftdictionarystruct

解决方案


假设 data.offings 等于

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
]

推荐阅读