Created
June 14, 2021 07:31
-
-
Save fxm90/3113ba447cc7275836591497a0c2ee47 to your computer and use it in GitHub Desktop.
Counterpart methods to `mapValues(_:)` and `compactMapValues(_:)`
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
// | |
// Dictionary+MapKeys.swift | |
// | |
// Created by Felix Mau on 14.06.21. | |
// Copyright © 2021 Felix Mau. All rights reserved. | |
// | |
extension Dictionary { | |
/// Returns a new dictionary containing the keys transformed by the given closure. | |
/// The values of this dictionary stay the same. | |
func mapKeys<T: Hashable>(_ transform: (Key) -> T) -> [T: Value] { | |
reduce(into: [T: Value]()) { | |
let mappedKey = transform($1.key) | |
$0[mappedKey] = $1.value | |
} | |
} | |
/// Returns a new dictionary containing the keys transformed by the given closure and filtered by `nil` results. | |
/// The values of this dictionary stay the same. | |
func compactMapKeys<T: Hashable>(_ transform: (Key) -> T?) -> [T: Value] { | |
reduce(into: [T: Value]()) { | |
guard let mappedKey = transform($1.key) else { return } | |
$0[mappedKey] = $1.value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment