Created
April 14, 2018 09:14
-
-
Save atomoil/6233250980e26eb7b1409444b6d3e4cc 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
/** | |
// 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