What's the most efficient way to split an array of objects into multiple arrays based on a property?
For example, say we have the following items:
var items = [
Food(name: "Cupcake", foodType: .dessert),
Food(name: "Banana", foodType: .fruit),
Food(name: "Grandma's Soup", foodType: .custom("home-made"),
Food(name: "Ice-cream", foodType: .dessert),
]
What's the best way to split it into the following arrays based on foodType:
[Food(name: "Cupcake", foodType: .dessert), Food(name: "Ice-cream", foodType: .dessert)]
[Food(name: "Banana", foodType: .fruit)],
[Food(name: "Grandma's Soup", foodType: .custom("home-made")]
In my example, foodType is an enum that looks like this:
enum FoodType {
case dessert
case fruit
case custom(string)
case vegetable
}
Normally I'd make my enum conform to CaseIterable and then loop over allCases, however, given that I'm using associated values, that's not possible.
My Approach:
var sections: [FoodType: [String]] = [:]
items.forEach {
sections[$0.foodType] = (sections[$0.foodType] ?? []) + [$0.name]
}
.custom("foo")and.custom("bar"), do you want them to be in the same group or different groups?