Created
April 3, 2018 23:02
-
-
Save Palleas/2f515818ca05752d45d6bdbd47d27684 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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