将多级数组转换为字典

时间:2019-06-24 15:06:30

标签: ios swift swift3

我有以下模型:Car和CarType,并在下面创建一系列汽车。我想将汽车数组转换为字典[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]

我想将汽车数组转换为[String: [Car]]字典。

1 个答案:

答案 0 :(得分:2)

有一个API:Dictionary(grouping:by:)

this