My data structure has an enum as a key, I would expect the below to decode automatically. Is this a bug or some configuration issue?
import Foundation
enum
Following from Imanou's answer, and going super generic. This will convert any RawRepresentable enum keyed dictionary. No further code required in the Decodable items.
public extension KeyedDecodingContainer
{
func decode(_ type: [K:V].Type, forKey key: Key) throws -> [K:V]
where K: RawRepresentable, K: Decodable, K.RawValue == R,
V: Decodable,
R: Decodable, R: Hashable
{
let rawDictionary = try self.decode([R: V].self, forKey: key)
var dictionary = [K: V]()
for (key, value) in rawDictionary {
guard let enumKey = K(rawValue: key) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "Could not parse json key \(key) to a \(K.self) enum"))
}
dictionary[enumKey] = value
}
return dictionary
}
}