* Add Grouped and Keyed * Add `Key` to `combine` closure * Split `keyed(by:)` into two overloads * Rename uniquingKeysWith → resolvingConflictsWith * Keep latest instead of throwing on collision
3.5 KiB
Grouped
Groups up elements of a sequence into a new Dictionary, whose values are Arrays of grouped elements, each keyed by the result of the given closure.
let fruits = ["Apricot", "Banana", "Apple", "Cherry", "Avocado", "Coconut"]
let fruitsByLetter = fruits.grouped(by: { $0.first! })
// Results in:
// [
// "B": ["Banana"],
// "A": ["Apricot", "Apple", "Avocado"],
// "C": ["Cherry", "Coconut"],
// ]
If you wish to achieve a similar effect but for single values (instead of Arrays of grouped values), see keyed(by:).
Detailed Design
The grouped(by:) method is declared as a Sequence extension returning
[GroupKey: [Element]].
extension Sequence {
public func grouped<GroupKey>(
by keyForValue: (Element) throws -> GroupKey
) rethrows -> [GroupKey: [Element]]
}
Complexity
Calling grouped(by:) is an O(n) operation.
Comparison with other languages
| Language | Grouping API |
|---|---|
| Java | groupingBy |
| Kotlin | groupBy |
| C# | GroupBy |
| Rust | group_by |
| Ruby | group_by |
| Python | groupby |
| PHP (Laravel) | groupBy |
Naming
All the surveyed languages name this operation with a variant of "grouped" or "grouping". The past tense grouped(by:) best fits Swift's API Design Guidelines.
Customization points
Java and C# are interesting in that they provide multiple overloads with several points of customization:
- Changing the type of the groups.
- E.g. the groups can be Sets instead of Arrays.
- Akin to calling
.transformValues { group in Set(group) }on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group.
- Picking which elements end up in the groupings.
- The default is the elements of the input sequence, but can be changed.
- Akin to calling
.transformValues { group in group.map(someTransform) }on the resultant dictionary, but avoiding the intermediate allocation of Arrays of each group.
- Changing the type of the outermost collection.
- E.g using an
OrderedDictionary,SortedDictionaryorTreeDictionaryinstead of the default (hashed, unordered)Dictionary. - There's no great way to achieve this with the
grouped(by:). One could wrap the resultant dictionary in an initializer to one of the other dictionary types, but that isn't sufficient: Once theDictionaryloses the ordering, there's no way to get it back when constructing one of the ordered dictionary variants.
- E.g using an
It is not clear which of these points of customization are worth supporting, or what the best way to express them might be.