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

Thanks for reading and happy coding! 🙏