ios - 根据字段值 Swift 分组对象
问题描述
我收到了来自 Firebase Firestore(优惠)的一系列文档。我有一个字段,其中包含项目应分组的部分的值。我想根据该字段值对所有项目进行分组,然后将它们放入单独的部分结构中。即,如果对象具有组的键值对,["section": "featured"]
则将创建所有具有“特色”的对象作为部分。
这是我的报价结构:
struct Offer: Codable, Hashable {
var documentID: String? = nil
let title: String
let subTitle: String
let section: String
}
这是我的部分结构:
struct Section: Decodable, Hashable {
let title: String
let subTitle: String?
let offers: [Offer]
}
我追求的结果如下,每个“部分”值的部分,这是我的数据的快照;
[
{
"title": "Here's the title",
"subTitle": "Here's the subTitle",
"section": "featured"
},
{
"title": "Here's the title",
"subTitle": "Here's the subTitle",
"section": "featured"
},
{
"title": "Here's the title",
"subTitle": "Here's the subTitle",
"section": "popular"
},
{
"title": "Here's the title",
"subTitle": "Here's the subTitle",
"section": "latest"
}
]
所以我的结果应该返回 3 个部分,2 个项目是特色项目,1 个项目是流行和最新的。
解决方案
let offersBySection = Dictionary(grouping: offers, by: \.section)
推荐阅读
- shopware - Shopware6:如何删除所有演示数据
- c# - 如何使用 linq 获取具有更大索引的行
- ghost-blog - 幽灵主题图片拉伸问题
- java - Gson - 从 json 字符串转换为对象列表
- javascript - Puppeteer - 对同一页面的“加载”和“networkidle0”执行不同的操作
- java - 用 javac 编译两个源文件夹
- javascript - 如何在 Hugo 的部分模板中包含静态文件
- python - 如何将文件夹中的所有图像垂直合并/附加/堆叠/粘贴到新图像
- flutter - Flutter 子类 Scaffold,因此我可以确保 Drawer 和 BottomNavigationBar 始终存在
- java - 在hibernate中找出数据库条目和存储在应用程序中的条目之间的最快方法