Swap keys and values of a Dictionary in Swift

Swap keys and values of a Dictionary in Swift

By rizwanahmed | ohmyswift | 24 May 2021


Dictionaries are one of the most commonly used data structures. Dictionaries come with keys and values where the keys are unique. Sometimes, there might be a situation where we would want to swap the keys and values of a dictionary. Let’s see how to swap keys and values of a dictionary in swift.

 

While doing so, we need to make sure that the values which are converted to keys are hashable and unique, else the conversion will fail.

extension Dictionary where Value: Hashable {
    struct DuplicateValuesError: Error { }
    init?(swappingKeysAndValues dict: [Value:  Key]) {
        do {
            try self.init(dict.lazy.map { ($0.value, $0.key) },
                          uniquingKeysWith: { _,_ in throw DuplicateValuesError() })
        } catch {
            return nil
        }
    }
}

 

let dict = [1 : "A", 2 : "B", 3 : "C", 4 : "D", 5 : "E"]
if let swappedDict = Dictionary(swappingKeysAndValues: dict) {
    print(swappedDict)
}else{
    print("Unable to swap keys and values")
}

 

Result:
["A": 1, "D": 4, "C": 3, "E": 5, "B": 2]

 

The given code tries to swap keys and values of the given dictionary, and in case something goes wrong, it fails gracefully.

Do you know a better approach than the one mentioned in this article? Let me know in the comments.

 

Credits and References

[1] https://stackoverflow.com/a/50008875

[2] https://cocoacasts.com/what-is-a-lazymapcollection-in-swift

About the author

App of the week

Winya (iOS, and iPadOS)

Summary - Stream games from iPhone/iPad like a PRO. The UX of the app is amazing. It gets you started in seconds.

Key highlights - Stream games, Unlimited streaming, pause streaming, control video quality with precision, control audio quality with precision

Homepage

iOS, and iPadOS download link

More articles

This post was originally posted at https://ohmyswift.com/blog/2021/03/24/swap-keys-and-values-of-a-dictionary/

How do you rate this article?

2


rizwanahmed
rizwanahmed

iOS developer. Writes about Swift and iOS development.


ohmyswift
ohmyswift

Weekly articles about Swift and iOS development.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.