Last active
February 4, 2020 13:55
-
-
Save aryaxt/ed9de5b14956df6f0efa to your computer and use it in GitHub Desktop.
Swift Array GroupBy
This file contains hidden or 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 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 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated code for swift 3