Skip to content

Instantly share code, notes, and snippets.

@naithar
Created May 23, 2016 10:14
Show Gist options
  • Save naithar/4bfbdf044dca20a3ea7740d2da9ec8c5 to your computer and use it in GitHub Desktop.
Save naithar/4bfbdf044dca20a3ea7740d2da9ec8c5 to your computer and use it in GitHub Desktop.
public extension SequenceType {
/// Categorises elements of self into a dictionary, with the keys given by keyFunc
func categorise<U : Hashable>(@noescape keyFunc: Generator.Element -> U) -> [U:[Generator.Element]] {
var dict: [U:[Generator.Element]] = [:]
for el in self {
let key = keyFunc(el)
if case nil = dict[key]?.append(el) { dict[key] = [el] }
}
return dict
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment