Skip to content

Instantly share code, notes, and snippets.

@atomoil
Created April 14, 2018 09:14
Show Gist options
  • Save atomoil/6233250980e26eb7b1409444b6d3e4cc to your computer and use it in GitHub Desktop.
Save atomoil/6233250980e26eb7b1409444b6d3e4cc to your computer and use it in GitHub Desktop.
/**
// Example:
// dictionary will be a dictionary with keys for every unique value of object.propertyToGroupBy
// the value of each being an array of objects
var dictionary = arrayOfObjects.group { $0.propertyToGroupBy }
// dictionary will be a dictionary with 2 keys 'Important' and 'Other' each containing an array of ItemType objects
var dictionary = arrayOfObjects.group { (item:ItemType) -> String in
if item.differentPropertyToGroupBy == "some value" {
return "Important"
} else {
return "Other"
}
}
*/
public extension Sequence {
func group<U: Hashable>(by key: (Iterator.Element) -> U) -> [U: [Iterator.Element]] {
var categories: [U: [Iterator.Element]] = [:]
for element in self {
let key = key(element)
if case nil = categories[key]?.append(element) {
categories[key] = [element]
}
}
return categories
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment