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.
Thanks for reading!
WRITTEN BY
Andrew Lord
A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.
Want to read more?
Here are some other articles you may enjoy.