Codable synthesis for enums *without* associated values

Assume we have a simple enumeration to represent the cardinal directions:

enum Direction {
    case N, S, E, W
}

Now let's say that we want to synthesize Codable conformance. I would have thought that the following would work:

enum Direction: Codable {
    case N, S, E, W
}

But Xcode 12.4 is telling me that I need to implement this conformance myself:

Type 'Direction' does not conform to protocol 'Decodable'
Type 'Direction' does not conform to protocol 'Encodable'

Does an enumeration like this need raw values—either explicitly or implicitly assigned—to qualify for automatic Codable conformance?

Yes, because otherwise what values will be put into the resulting JSON?

Note that the encoded result could be stored in a JSON file, a property list, or some other format, but in any case I honestly wasn't sure what values would be generated. I guess I just assumed that each case would be assigned an integer or string value simply for the purpose of Codable conformance after finding a number of highly-ranked Google search results that seem to imply this is possible:

As of Swift 5 only enums without associated values have automatic conformance to Codable. For example, to make our EditSubview conform to Codable we only need to indicate the conformance in the declaration.

enum EditSubview: Codable {
   case headers
   case query
   case body
}

So is it safe to assume that the information in these blog posts is inaccurate?

Yes, that code won't compile. Note that if you follow the link in that blog post to its corresponding GitHub repository, the EditSubview enum looks like this:

enum EditSubview: String, Codable {
    case headers
    case query
    case body
}

which does compile since it has a raw type that conforms to Codable.

So I think that's probably just an oversight or editing error or something like that in the blog post.

Ahhh I see—thanks for clarifying! Good to know that I wasn't missing something here. :+1:

Terms of Service

Privacy Policy

Cookie Policy