Apologies if this has been discussed before, a quick search of threads regarding keyDecodingStrategy
didn't turn up anything that looked like it addressed this specific question.
Consider the following simple model:
struct User: Decodable {
enum AccountType: String, Decodable {
case basic, pro, proUltra
}
var accountType: AccountType
}
This successfully decodes the payload {"account_type": "pro"}
but fails to decode {"account_type": "pro_ultra"}
with the error "Cannot initialize AccountType from invalid String value pro_ultra
". The solution is to specify the raw value of the proUltra
case manually, so that the enum
is defined as
enum AccountType: String, Decodable {
case basic, pro, proUltra = "pro_ultra"
}
This case encoding must be specified for all cases of all enum
s where the case name consists of more than one word. However, when a JSONDecoder
is decoding User
it must already have the context to know that the account_type
key in the payload must map to the accountType
property. This is easily accomplished via a keyDecodingStrategy
of convertFromSnakeCase
, but that context is left unused when decoding String
-type enum
s.
Are there configuration options I'm not aware of that would enable this sort of decoding for enum
payloads without having to specify the raw values explicitly? If not, should this use-case be supported?
I would imagine it's exceedingly rare for an API to provide payloads which look like {"account_type": "proUltra"}
, so IMO it would be sensible default behavior to convert enum
payloads using the same strategy that keyDecodingStrategy
uses—however, I would imagine this is off the table due to backwards compatibility concerns. Options I can think of off-hand would be to provide a new configuration property on JSONDecoder
, something like stringEnumDecodingStrategy
, which could either be its own type or just be of type KeyDecodingStrategy
. Alternatively, String, Decodable
enum
s could offer a static
property (e.g. mimicKeyDecodingStrategy
) that would indicate that the enum payload should be decoded using the same strategy by which keys are converted.
Interested to hear other's thoughts on this topic!