Digital Tip #8: Getting all keys for a concrete value in a dictionary - Digital Leaves
post-template-default,single,single-post,postid-1920,single-format-standard,ajax_fade,page_not_loaded,,select-theme-ver-3.7,wpb-js-composer js-comp-ver-5.0.1,vc_responsive

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:

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!

Ignacio Nieto is the owner of the Digital Leaves blog, he loves building successful products that improve people’s lives. He has expertise in iOS, Full Stack JS, Android, RESTful backends, OAuth and cryptography.

No Comments

Post a Comment

Join the Digital Tips List
Want to become a freelance iOS developer or improve your skills? Subscribe to the Digital Tips list for weekly tips, useful tutorials and more to help you grow as a developer.
I hate spam, and I promise I'll keep your email address safe.