Little Snippets #1: Group By in Swift 3

A short implementation of the classic ‘group by’ function in Swift 3 as an Array extension.

Fernando Martín Ortiz
iOS App Development

--

Given an array of elements, and a criteria function, grouped(by:) transforms that array into a dictionary with the keys that the criteria function returns.

The criteria function takes an Element and returns its classification. For example, if you want to separate even numbers from odd ones, your criteria closure will return “even”, or “odd”.

I often use this for separating elements by creation date.

I hope this will help you. If you know a better way of doing this, please let me know below, in the comments! Thanks! 🙌

--

--