Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Map the keys of a dictionary to a different type

Published on · Updated on
1 minute read

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!

Like what you read? Please share the article.

Avatar of Andrew Lord

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