Skip to content

Instantly share code, notes, and snippets.

@Palleas
Created April 3, 2018 23:02
Show Gist options
  • Save Palleas/2f515818ca05752d45d6bdbd47d27684 to your computer and use it in GitHub Desktop.
Save Palleas/2f515818ca05752d45d6bdbd47d27684 to your computer and use it in GitHub Desktop.
extension Sequence {
func groupBy<K: Hashable>(_ kp: KeyPath<Iterator.Element, K>) -> [K: [Iterator.Element]] {
// Creating the resulting dictionary
return reduce([:]) { grouped, item in
let key = item[keyPath: kp]
var copy = grouped
if copy[key] == nil {
copy[key] = []
}
copy[key]?.append(item)
return copy
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment