Collections ยท SWIFT RECIPE

Group values by a key

Create a dictionary of arrays from a collection.

main.swift
let words = ["apple", "ant", "bear", "bird"]
let groups = Dictionary(grouping: words) { $0.first! }
for key in groups.keys.sorted() {
    print("\(key): \(groups[key]!)")
}

How it works

The grouping initializer collects source values into arrays under each key. Sort dictionary keys before displaying them instead of assuming an iteration order.

Keep in mind

These literals are nonempty. Handle empty strings when accepting outside input.

Read the Swift language reference