BetterCodable icon indicating copy to clipboard operation
BetterCodable copied to clipboard

Addition of @KeyContainer for encoding/decoding dictionaries

Open Strobocop opened this issue 5 years ago • 3 comments

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.

Strobocop avatar Jan 24 '20 19:01 Strobocop

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 avatar Jan 26 '20 04:01 marksands

@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?

StevenSorial avatar Jul 12 '21 03:07 StevenSorial

@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.

marksands avatar Jul 12 '21 04:07 marksands