I have a some nested swift classes that are automatically decoded from JSON using the Decodable protocol. Everything works except this one enum.
The json data is a capitalised string of either Open or Fulfilled.
If I use this enum, everything decodes perfectly fine:
enum Status: String, Codable {
case Open, Fulfilled
}
however i'm trying to get the cases to not use capitalized like this:
enum Status: String, Codable {
case open, fulfilled
private enum CodingKeys: String, CodingKey {
case open = "Open"
case fulfilled = "Fulfilled"
}
}
This gives me a decoding error saying:
debugDescription: "Cannot initialize Status from invalid String value Open"
Do CodingKeys not work like this for enums?
Do CodingKeys not work like this for enums?Joakim covers what to do here, but to answer this: there is a defaultCodableimplementation for things which areRawRepresentableby each of the "base"Codabletypes (String,Int,Bool, etc.). The one forStringencodes the raw value directly, andCodingKeysare not involved at all — because you get this default implementation, yourCodingKeysenum has no influence over the effective behavior.