Home > OS >  Group array by more than one property swift
Group array by more than one property swift

Time:09-30

Swift provides a method that converts array to dictionary on the basis of single property. Is it possible to group array to dictionary on the basis of more than one property. Something like following

Dictionary(grouping: array, by: { $0.name && $0.age })

CodePudding user response:

You can group by anything that can become a key, in other words, by anything that is Hashable.

If you need to combine multiple properties, define a new type:

struct GroupingKey: Hashable {
   let name: String
   let age: Int
}

Dictionary(grouping: array, by: { GroupingKey(name: $0.name, age: $0.age) })
  • Related