-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add extension for converting dictionary keys
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
Sources/AppFoundations/Extensions/Dictionary/Dictionary+KeyConversion.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |