Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active August 29, 2017 16:25
Show Gist options
  • Save jakebromberg/424c8ebdcf7bffb2ffd6f63a2556068e to your computer and use it in GitHub Desktop.
Save jakebromberg/424c8ebdcf7bffb2ffd6f63a2556068e to your computer and use it in GitHub Desktop.
Group elements in a sequence. Note that this implementation predates Swift 4's `grouping` operation
extension Sequence {
typealias Element = Iterator.Element
func groupBy<T: Hashable>(grouper: (Element) -> (T)) -> Dictionary<T, [Element]> {
var groups = [T : [Element]]()
for element in self {
let groupKey = grouper(element)
var group = groups[groupKey] ?? [Element]()
group.append(element)
groups[groupKey] = group
}
return groups
}
}
let grouped = (0...5).groupBy { x in
return x % 2 == 0 ? "Even" : "Odd"
}
print(grouped) // ["Odd": [1, 3, 5], "Even": [0, 2, 4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment