Skip to content

Commit

Permalink
Add extension for converting dictionary keys
Browse files Browse the repository at this point in the history
  • Loading branch information
mpdifran committed Oct 21, 2023
1 parent 0e57f3e commit d1dffa9
Showing 1 changed file with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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<NewKey>(_ converter: (Key) -> NewKey?) -> [NewKey : Value] {
var newDictionary = [NewKey : Value]()

keys.forEach { (key) in
if let newKey = converter(key) {
newDictionary[newKey] = self[key]
}
}

return newDictionary
}
}

0 comments on commit d1dffa9

Please sign in to comment.