Skip to content

Instantly share code, notes, and snippets.

@s3cur3
Forked from christianselig/milkshake.swift
Last active March 20, 2021 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s3cur3/63aa3ea34ef36534c1b011ac75fc56ea to your computer and use it in GitHub Desktop.
Save s3cur3/63aa3ea34ef36534c1b011ac75fc56ea to your computer and use it in GitHub Desktop.
Generic versions of transforming Dictionary keys and values, inspired by https://twitter.com/ChristianSelig/status/1372961695346352130
extension Dictionary {
func mapKeys<NewKey>(_ transform: (Key) -> NewKey) -> [NewKey: Value] {
reduce(into: [NewKey: Value]()) { result, item in
result[transform(item.key)] = item.value
}
}
}
/// 🥤
extension Dictionary where Key: RawRepresentable {
func rawConversion<NewKey>() -> [NewKey: Value] where NewKey == Key.RawValue {
mapKeys(\.rawValue)
}
}
@s3cur3
Copy link
Author

s3cur3 commented Mar 20, 2021

Updated to match the naming scheme of the existing Dictionary.mapValues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment