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:

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!