ios - 快速添加基于键的分组字典元素的值
问题描述
我有一系列名为“产品”的产品。我已将数组分组,如下所示。
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.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
]
推荐阅读
- byte-buddy - 有没有办法获得匹配的 MethodDescription?
- javascript - 有没有办法对 Web Notification API 进行 Jest 测试和监视?
- tinymce - 在 TinyMCE 中是否有允许在使用将上传的图像保存在服务器上的后端图像加载处理程序时粘贴图像的功能?
- python - 使用 Django-storages 分段上传到 S3
- ios - 由于打印语句重复 4 次,firestore 文档中的字段值增加了错误的数字
- wso2 - API 定义中缺少可见角色
- sql - Athena 中的更新表
- reactjs - 在 React 中动态渲染 base64 编码的 SVG
- typescript - 我的 Stripe 签名密钥是什么,我在哪里可以找到它?
- javascript - threejs如何旋转transformcontrol本身