Skip to content

Instantly share code, notes, and snippets.

@dfelber
Created November 4, 2016 14:16
Show Gist options
  • Save dfelber/e3c0e8cc67034d28b692433b80243bbf to your computer and use it in GitHub Desktop.
Save dfelber/e3c0e8cc67034d28b692433b80243bbf to your computer and use it in GitHub Desktop.
public extension Sequence {
func categorise<U : Hashable>(_ key: (Iterator.Element) -> U) -> [U:Int] {
var dict: [U:Int] = [:]
self.forEach { el in
let key = key(el)
dict[key] = (dict[key] ?? 0) + 1
}
return dict
}
}
print([1, 4, 7 ,4, 2, 2, 4, 7, 1, 2].categorise{ $0 })
// [7: 2, 2: 3, 4: 3, 1: 2]
print(["a", "a", "b", "b", "b", "b", "c"].categorise{ $0 })
// ["b": 4, "a": 2, "c": 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment