diff --git a/Sources/AppFoundations/Extensions/Dictionary/Dictionary+KeyConversion.swift b/Sources/AppFoundations/Extensions/Dictionary/Dictionary+KeyConversion.swift new file mode 100644 index 0000000..ecc5913 --- /dev/null +++ b/Sources/AppFoundations/Extensions/Dictionary/Dictionary+KeyConversion.swift @@ -0,0 +1,26 @@ +// +// Dictionary+KeyConversion.swift +// +// +// Created by Mark DiFranco on 2023-10-21. +// + +import Foundation + +public extension Dictionary { + + /// Converts `self` into a new dictionary with a different type of key. + /// - parameter converter: The closure to use to convert the keys' types. + /// - returns: A new dictionary, with the new type as the key. + func convertKeys(_ converter: (Key) -> NewKey?) -> [NewKey : Value] { + var newDictionary = [NewKey : Value]() + + keys.forEach { (key) in + if let newKey = converter(key) { + newDictionary[newKey] = self[key] + } + } + + return newDictionary + } +}