Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Counterpart methods to `mapValues(_:)` and `compactMapValues(_:)`
//
// 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