Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift dictionary get key for value

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?

like image 587
mginn Avatar asked Nov 30 '14 21:11

mginn


1 Answers

Swift 3: a more performant approach for the special case of bijective dictionaries

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 
like image 77
dfrib Avatar answered Oct 04 '22 20:10

dfrib