Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group array by more than one property swift

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading