-
-
Save halftrue/759c24b7ef6ce37c3c6757b24b1110a7 to your computer and use it in GitHub Desktop.
Find keys mapped to a value in Swift dictionary
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
extension Dictionary where Value: Equatable { | |
/// Returns all keys mapped to the specified value. | |
/// ``` | |
/// let dict = ["A": 1, "B": 2, "C": 3] | |
/// let keys = dict.keysForValue(2) | |
/// assert(keys == ["B"]) | |
/// assert(dict["B"] == 2) | |
/// ``` | |
func keysForValue(value: Value) -> [Key] { | |
return flatMap { (key: Key, val: Value) -> Key? in | |
value == val ? key : nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment