Skip to content

Instantly share code, notes, and snippets.

@sebj
Created January 22, 2021 23:27
Show Gist options
  • Save sebj/a5b87a3aac66fc6279ce8a0dca2b5337 to your computer and use it in GitHub Desktop.
Save sebj/a5b87a3aac66fc6279ce8a0dca2b5337 to your computer and use it in GitHub Desktop.
Dictionary Extension: Map Keys
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