Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created November 16, 2016 04:10
Show Gist options
  • Select an option

  • Save khanlou/c328756a303c6cf5961e53d11ca76737 to your computer and use it in GitHub Desktop.

Select an option

Save khanlou/c328756a303c6cf5961e53d11ca76737 to your computer and use it in GitHub Desktop.
//stolen from @publicextension
extension Sequence {
func groupBy<T>(groupBy: (Iterator.Element) -> T) -> [T: [Iterator.Element]] {
var result: [T: [Iterator.Element]] = [:]
self.forEach { element in
let groupKey = groupBy(element)
result[groupKey] = (result[groupKey] ?? []) + [element]
}
return result
}
}
let dict = [
"test": "value",
"a222": "value1",
"test2": "value3",
]
let p = dict.groupBy(groupBy: { $0.0.characters.count })
print(p)
let g = dict.keys.groupBy(groupBy: { $0.characters.count })
print(g)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment