Created
October 5, 2018 15:11
-
-
Save AKiniyalocts/7cbea5fef147229a3eeecf45b8bf14c3 to your computer and use it in GitHub Desktop.
GroupBy.swift
This file contains 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
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