Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addition of @KeyContainer for encoding/decoding dictionaries #15

Open
Strobocop opened this issue Jan 24, 2020 · 3 comments
Open

Addition of @KeyContainer for encoding/decoding dictionaries #15

Strobocop opened this issue Jan 24, 2020 · 3 comments
Labels
enhancement New feature or request

Comments

@Strobocop
Copy link

Strobocop commented Jan 24, 2020

Ole Begemann came up with a nice use case for fixing a shortcoming of Codable when dealing with Dictionaries that have a String based Enum key. Currently, these unexpectedly encode/decode as arrays rather than dictionary representations

https://gist.github.com/ole/5c31ca9e2919c815029784ef3b8fdc0d

If this is too specific of a use case, it might not make sense to include it, but I believe it solves a real problem that I have faced with Codable. What do you think about including this or a similar implementation? If you think it's useful, this package feels like a good home for it.

@marksands
Copy link
Owner

That's super interesting, thanks for the tip! The accompanying bugs.swift.org post has a lot of good info on that as well. I'll spend some time digging into these nuances and see what I can come up with.

@marksands marksands added the enhancement New feature or request label Jun 2, 2020
@StevenSorial
Copy link
Contributor

StevenSorial commented Jul 12, 2021

@Strobocop I have this extension in my code

extension KeyedDecodingContainer {
  func decodeRawKeyedDict<K: RawRepresentable, V: Decodable>(
    _ type: [K: V].Type,
    forKey key: Key
  ) throws -> [K: V] where K.RawValue: Decodable & Hashable {
    let rawDict = try decode([K.RawValue: V].self, forKey: key)
    let tupleArray = rawDict.compactMap { key, value in
      K(rawValue: key).flatMap { ($0, value) }
    }
    return .init(tupleArray) { first, second in first }
  }
}

@marksands Open for a PR?

@marksands
Copy link
Owner

@Stevenmagdy Appreciate the offer but no thanks. I'm still on the fence with supporting something similar to KeyedContainer. There are a lot of bugs-used-as-features in regards to Dictionary de/en/coding right now so I've been hoping to see Swift make a decision here or tell us this is the bed we must lie in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants