Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
SDK
- Xcode 10.2+
Framework
- Swift Standard Library
Declaration
Parameters
values
A sequence of values to group into a dictionary.
keyForValue
A closure that returns a key for each element in
values
.
Discussion
The arrays in the “values” position of the new dictionary each contain at least one element, with the elements in the same order as the source sequence.
The following example declares an array of names, and then creates a dictionary from that array by grouping the names by first letter:
The new students
dictionary has three entries, with students’ names grouped by the keys "E"
, "K"
, and "A"
.