-2

My Data Model :

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

I have a array of data ,

        var catProducts = [ProductResponse]()

Ok , I want to group the products having the same catagories[0].name in one array . and make the final array having grouped Products with the same catagories[0].name

var myfinalDataArray = [["title": [ProductResponse]], ....]

like eg ,

["cata1": [list of products with ProductResponse .catagory[0].name == cata1]], "cat2": [list of products with the ProductResponse
catagory[0].name == cat2, ....]

key will be from ProductResponse . catagories[0].name

Kiran
  • 125
  • 2
  • 12
  • Use [`Dictionary(grouping:by:)`](https://developer.apple.com/documentation/swift/dictionary/3127163-init) – vadian Mar 15 '19 at 08:40

1 Answers1

0

You could use:

Dictionary(grouping: catProducts, by: {
  $0.categories?.first?.name 
})

Which should return a dictionary [String : ProductResponse], containing catProducts grouped by the first category name.

Some good answers to a very similar problem in this question: How to group by the elements of an array in Swift

user1636130
  • 1,615
  • 5
  • 29
  • 47