Map the dictionary keys into a different type
Swift collections provide an API to convert the Values of a Dictionary, but we came across a scenario where we need to change the type of keys alone. Let's dive into the scenario.
When
We were writing a generic API framework that fetches the account contacts from the server and persists into the database. Since it’s an api and it accepts the query parameters in a [String: Any] format. Dictionary Keys that are of type string can be easily manipulated with a typo.
Then
To avoid the unnecessary typos in the query we tend to force the Key into an enum just like Codable CodingKey. New QueryParam Dictionary looks like [ParamKey: Any]
Fix
The actual problem is when we pass the QueryParam into URLSession. Since URLSession accepts [String: Any], we should map our ParamKeys into String. We were looking for a native api from the swift collection, unfortunately, we couldn’t find one. So we wrote one for our own.
Usage
The above little candy helped us to accomplish our goal. Not sure why there is no native api from the swift collection for this simple conversation.
That’s it for this time! Feel free to comment if you have questions and follow to get notifications about future articles.
“Be the senior engineer you needed as a junior.” — Someone
👏👏👏👏👏👏👏