Skip to content

Instantly share code, notes, and snippets.

@aryaxt
Last active February 4, 2020 13:55
Show Gist options
  • Save aryaxt/ed9de5b14956df6f0efa to your computer and use it in GitHub Desktop.
Save aryaxt/ed9de5b14956df6f0efa to your computer and use it in GitHub Desktop.
Swift Array GroupBy
extension Sequence {
func groupBy<G: Hashable>(closure: (Iterator.Element)->G) -> [G: [Iterator.Element]] {
var results = [G: Array<Iterator.Element>]()
forEach {
let key = closure($0)
if var array = results[key] {
array.append($0)
results[key] = array
}
else {
results[key] = [$0]
}
}
return results
}
}
// Usage
var users: [User]
users.gourpBy { $0.age }
@NinoScript
Copy link

This one was closer to what I was looking for: http://stackoverflow.com/a/31220067/1904287

@aryaxt
Copy link
Author

aryaxt commented Jun 10, 2017

Updated code for swift 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment