Created
January 22, 2021 23:27
-
-
Save sebj/a5b87a3aac66fc6279ce8a0dca2b5337 to your computer and use it in GitHub Desktop.
Dictionary Extension: Map Keys
This file contains hidden or 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
extension Dictionary { | |
/// Returns a new dictionary containing the keys of this dictionary transformed | |
/// by the given closure with the existing values. | |
/// | |
/// - Parameter transform: A closure that transforms a key. `transform` | |
/// accepts each key of the dictionary as its parameter and returns a | |
/// transformed key of the same or of a different type. | |
/// - Returns: A dictionary containing the transformed keys and values of | |
/// this dictionary. | |
/// | |
/// - Complexity: O(*n*), where *n* is the length of the dictionary. | |
@inlinable func mapKeys<NewKey>(_ transform: (Key) throws -> NewKey) rethrows -> [NewKey: Value] { | |
try reduce(into: [NewKey: Value]()) { dictionary, keyValue in | |
let key = try transform(keyValue.key) | |
dictionary[key] = keyValue.value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment