Skip to content

Instantly share code, notes, and snippets.

@christianselig
Last active March 20, 2021 11:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christianselig/ea4a3e8a7816bfff6a10668b59f2d629 to your computer and use it in GitHub Desktop.
Save christianselig/ea4a3e8a7816bfff6a10668b59f2d629 to your computer and use it in GitHub Desktop.
A beautiful milkshake where the ingredients are Sean Heber, Yakov Shapovalov, and Hunter Meyer.
/// 🥤
extension Dictionary where Key: RawRepresentable {
func rawConversion<NewKey>() -> Dictionary<NewKey, Value> where NewKey == Key.RawValue {
let newDict: [NewKey: Value] = self.reduce(into: [:]) { (result, item) in
result[item.key.rawValue] = item.value
}
return newDict
}
}
@photovirus
Copy link

photovirus commented Mar 19, 2021

You can make it an (almost) one-liner like this:

    func rawConversion<NewKey>() -> Dictionary<NewKey, Value> where NewKey == Key.RawValue {
        self.lazy.reduce(into: [:]) { (result, item) in
            result[item.key.rawValue] = item.value
        }
    }

@huntercmeyer
Copy link

To allow for type inferencing,

func rawConversion<NewKey>(to type: NewKey.Type) -> Dictionary<NewKey, Value> where NewKey == Key.RawValue

with the call site:

checklist2 = checklist1.rawConversion(to: String.self)

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