Skip to content

Instantly share code, notes, and snippets.

@kirkbyo
Created June 1, 2018 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirkbyo/fadc797bde3acec8b32f9b47fc2b6c4b to your computer and use it in GitHub Desktop.
Save kirkbyo/fadc797bde3acec8b32f9b47fc2b6c4b to your computer and use it in GitHub Desktop.
extension Dictionary where Value: Hashable {
/// Groups keys with common values together. Example:
/// ```
/// let groceryList = ["Apple": 2, "Oranges": 3, "Pears": 2]
/// groceryList.keysGroupedByValue
/// // => [2: ["Apple", "Pears"], 3: ["Oranges"]]
/// ```
public var keysGroupedByValue: [Value: [Key]] {
var commonalities: [Value: [Key]] = [:]
for (key, value) in self {
commonalities[value, default: []].append(key)
}
return commonalities
}
}
class Dictionary_ExtensionsTests: XCTestCase {
func testExtractKeysWithCommonValues() {
let testingDict = ["Oranges": 2, "Pears": 5, "Strawberries": 4, "Apples": 2]
let commonalities = testingDict.keysGroupedByValue
XCTAssert(commonalities == [2: ["Oranges", "Apples"], 5: ["Pears"], 4: ["Strawberries"]])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment