Search code examples
iosswiftswift3

Convert multilevel array to dictionary


I have following models: Car and CarType and I create array of cars below. I would like to convert that array of cars to dictionary [String: [Car]]

struct Car {
   let carId: Int
   let carName: String
   let carType: [Category]

   init(carId: Int, carName: String, carType: [Category]) {
                self.carId = carId
                self.carName = carName
                self.carType = carType
   }
}

struct Category {
   let categoryId: Int
   let categoryName: String
}

var cat1 = Category(categoryId: 123, categoryName: "Truck")
var cat2 = Category(categoryId: 123, categoryName: "Family")

let car1 = Car(carId: 1, carName: "Ford", carType: [cat1])
let car2 = Car(carId: 2, carName: "Honda", carType: [cat1, cat2])

let cars = [car1, car2]

I would like to convert cars array to [String: [Car]] dictionary.


Solution

  • There is an API: Dictionary(grouping:by:)

    let groupedCars = Dictionary(grouping: cars, by: {$0.carName})