Created
October 4, 2016 14:22
-
-
Save Palleas/115990fa585e86dc535a8313f815117f to your computer and use it in GitHub Desktop.
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 SequenceType { | |
func groupBy<Key: Hashable>(handler: (Generator.Element) -> Key) -> [Key: [Generator.Element]] { | |
var grouped = [Key: Array<Generator.Element>]() | |
self.forEach { item in | |
let key = handler(item) | |
if grouped[key] == nil { | |
grouped[key] = [] | |
} | |
grouped[key]?.append(item) | |
} | |
return grouped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Swift 3 you could do this as:
By actually setting a value in the case where the group doesn't exist, you save 2 calls in this example.