I'm using a swift dictionary of type [UIImage:UIImage], and I'm trying to find a specific key for a given value. In Objective-C I could use allKeysForValue, but there appears to be no such method for a Swift dictionary. What should I be using?
If the reverse dictionary lookup use case covers a bijective dictionary with a one to one relationship between keys and values, an alternative approach to the collection-exhaustive filter
operation would be using a quicker short-circuiting approach to find some key, if it exists.
extension Dictionary where Value: Equatable { func someKey(forValue val: Value) -> Key? { return first(where: { $1 == val })?.key } }
Example usage:
let dict: [Int: String] = [1: "one", 2: "two", 4: "four"] if let key = dict.someKey(forValue: "two") { print(key) } // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With