
Digital Tip #8: Getting all keys for a concrete value in a dictionary
The Digital Tip of the week is a very useful extension that I use in my dictionaries to get the keys that match a concrete key. The inverse operation is pretty easy for a dictionary, just calling dictionary[key], but as the same value may be assigned to multiple, different keys, I sometimes find it really handy to be able to quickly get all keys in a dictionary that are mapped to a concrete value. This is the extension I use:
1 2 3 4 5 6 7 8 9 10 |
import Foundation /** A useful extension to get all keys that match a concrete value in a Dictionary */ extension Dictionary where Value: Equatable { func keysForValue(_ value: Value) -> [Key] { return flatMap { (key: Key, val: Value) -> Key? in value == val ? key : nil } } } |
As you may recall from Sequence Hacking in Swift, Dictionaries are sequences, and as such, we can apply all the Sequence operations (such as map, flatMap, filter, etc). I hope this tip is useful to you too. Have anything to add? Do you have a favorite extension that you would like to share with us? Please, don’t hesitate to do so in the comments below!
❤️ Did you enjoy this article?
If you found this content useful, consider giving some love back by making a small bitcoin, ethereum or bitcoin cash donation. Thank you!

BTC: 331u8dLejzfssKY3cXm1DPPvtaibaS4S9z

ETH: 0x994ECE4B48144f5541B34D5f15a3D671e51D7E05

BCH: 1KejtFCcrv7X2ZgovpLgs6pwgqDo1KmrmS
No Comments