首页 > 解决方案 > 根据字段值 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 个项目是流行和最新的。

标签: iosswiftdictionarygrouping

解决方案


利用Dictionary(grouping:by:)

let offersBySection = Dictionary(grouping: offers, by: \.section)

推荐阅读