Created
June 1, 2018 19:06
-
-
Save kirkbyo/fadc797bde3acec8b32f9b47fc2b6c4b to your computer and use it in GitHub Desktop.
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 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