Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Created April 14, 2016 15:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ijoshsmith/a411775b78f107f1c51152c6eda9d665 to your computer and use it in GitHub Desktop.
Save ijoshsmith/a411775b78f107f1c51152c6eda9d665 to your computer and use it in GitHub Desktop.
Find keys mapped to a value in Swift dictionary
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
}
}
}
@ijoshsmith
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment