Group arrays by a criterion with Swift 4.0

January 04, 2019

Let's say you have an array, and you wanted to group each item in an array that have a common value. Swift 4.0 has a powerful grouping by feature to do so.

let developers = ["Eliad Moosavi", "Alex Nguyen", "Steve Jobs", "Bill Gates", "Dennis Ritchie", "Anders Hejlsberg"]

Group each name via their first initial. Below creates a Dictionary with keys that are the first name character and an array of names with the same first character.

let groupedByFirst = Dictionary(grouping: developers) { $0.first! }