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.
Winya: Live Stream Games
Become a Streamer by starting a live stream from your iPhone/iPad to Twitch/YouTube or any live streaming service of your choice. Download the app and become a creator now!
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.
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
About the author
- Rizwan Ahmed - iOS Engineer. Twitter - https://twitter.com/rizwanasifahmed