Skip to content

Instantly share code, notes, and snippets.

@tapi
Created February 6, 2015 14:24
Show Gist options
  • Save tapi/325f06bca45dd799ffc9 to your computer and use it in GitHub Desktop.
Save tapi/325f06bca45dd799ffc9 to your computer and use it in GitHub Desktop.
A generic groupby function that should work similarily to ruby's
/**
Group all items in a collection according to the value returned by a block.
:param: collection The collection whose items you want to group.
:param: groupBlock A block that returns a key for that value to be grouped by.
:returns: Returns a dictionary whose keys are the values returned by the groupBlock.
*/
func groupBy<V, K : protocol<Hashable, Equatable>, C : _ExtensibleCollectionType where C.Generator.Element == V>(collection: C, groupBlock: (V) -> K) -> [K: [V]] {
typealias ValueGroup = [V]
var grouped = [K: ValueGroup]()
for value in collection {
var key = groupBlock(value)
var group = grouped[key]
if let existingGroup = group {
group = existingGroup + [value]
}
else {
group = [value]
}
grouped[key] = group
}
return grouped
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment