Created
November 4, 2016 14:16
-
-
Save dfelber/e3c0e8cc67034d28b692433b80243bbf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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