Skip to content

Instantly share code, notes, and snippets.

@fxm90
Created June 14, 2021 07:31
Show Gist options
  • Save fxm90/3113ba447cc7275836591497a0c2ee47 to your computer and use it in GitHub Desktop.
Save fxm90/3113ba447cc7275836591497a0c2ee47 to your computer and use it in GitHub Desktop.
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