Find keys by value in Swift dictionary

Here’s a helper method that might come in handy when working with a Swift dictionary. It finds every key mapped to a particular value.


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
}
}
}

This is similar to the allKeysForObject(_:) method of NSDictionary, but it is generic so it can return an array of properly types keys, instead of an array of AnyObject.

This entry was posted in Swift and tagged . Bookmark the permalink.