Skip to content

Instantly share code, notes, and snippets.

@AKiniyalocts
Created October 5, 2018 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AKiniyalocts/7cbea5fef147229a3eeecf45b8bf14c3 to your computer and use it in GitHub Desktop.
Save AKiniyalocts/7cbea5fef147229a3eeecf45b8bf14c3 to your computer and use it in GitHub Desktop.
GroupBy.swift
extension Collection{
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
**/
public func groupBy<Value>(by keySelector:(Element) -> Value?) -> [Value?:[Element]]{
var groups = [Value?:[Element]]()
for (_, element) in self.enumerated(){
let key = keySelector(element)
if groups[key] != nil{
groups[key]!.append(element)
}else{
groups[key] = [element]
}
}
return groups
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment