Map the keys of a dictionary to a different type
The Swift standard library includes functions to transform the values of a Dictionary
, we need to add one ourselves to do the same to the keys.
There are situations this can come in handy such as converting a Dictionary
of analytics event parameters from using an internal enum for the keys to using Strings for reporting to our analytics API.
This neat little extension will allow us to do just that!
extension Dictionary {
func mapKeys<NewKeyT>(
_ transform: (Key) throws -> NewKeyT
) rethrows -> [NewKeyT: Value] {
var newDictionary = [NewKeyT: Value]()
try forEach { key, value in
let newKey = try transform(key)
newDictionary[newKey] = value
}
return newDictionary
}
}
I hope the article was useful. If you have any feedback or questions please feel free to reach out to me on Twitter.
Thanks for reading and happy coding!
Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.
Subscribe via RSS
Want to read more?
Here are some other articles you may enjoy.