我的数据模型:
struct ProductResponse: Codable {
var id: Int?
var name: String?
var slug: String?
var permalink: String?
var dateCreated: String?
var description: String?
var shortDescription: String?
var sku: String?
var price: String?
var regularPrice: String?
var salePrice: String?
var priceHtml: String?
var image: [ProductImageResponse]?
var catagories: [CatagoriesResponse]?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case slug = "slug"
case permalink = "permalink"
case dateCreated = "date_created"
case description = "description"
case shortDescription = "short_description"
case sku = "sku"
case price = "price"
case regularPrice = "regular_price"
case salePrice = "sale_price"
case priceHtml = "price_html"
case image = "images"
case catagories = "categories"
}
}
struct ProductImageResponse: Codable {
var id: Int?
var source: String?
var name: String?
var alt: String?
var position: Int
enum CodingKeys: String, CodingKey {
case id = "id"
case source = "src"
case name = "name"
case alt = "alt"
case position = "position"
}
}
struct CatagoriesResponse: Codable {
var id: Int
var name: String
var slug: String
enum CodingKeys: String, CodingKey{
case id = "id"
case name = "name"
case slug = "slug"
}
}
我有一个数据数组
var catProducts = [ProductResponse]()
好的,我想将具有相同类别[0] .name的产品归为一个数组。并将最终的产品分类为具有相同类别的产品[0] .name
var myfinalDataArray = [[“ title”:[ProductResponse]],....]
例如,
[“ cata1”:[带有ProductResponse .catagory [0] .name ==的产品列表 cata1],“ cat2”:[带有ProductResponse的产品列表
catagory [0] .name == cat2,....]键将来自ProductResponse。类别[0]。名称
答案 0 :(得分:0)
您可以使用:
Dictionary(grouping: catProducts, by: {
$0.categories?.first?.name
})
应该返回字典[String : ProductResponse]
,其中包含按第一类别名称分组的catProducts
。
此问题中一个非常相似的问题的一些很好的答案:How to group by the elements of an array in Swift