2

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?

1
  • 2
    Do CodingKeys not work like this for enums? Joakim covers what to do here, but to answer this: there is a default Codable implementation for things which are RawRepresentable by each of the "base" Codable types (String, Int, Bool, etc.). The one for String encodes the raw value directly, and CodingKeys are not involved at all — because you get this default implementation, your CodingKeys enum has no influence over the effective behavior. Commented Feb 22, 2023 at 16:54

1 Answer 1

4

Since the raw value type of your enum is String you can assign the correct strings directly to your enum items

enum Status: String, Codable {
    case open = "Open"
    case fulfilled = "Fulfilled"
}

If you for some reason do not want to do it this way then you need to implement a custom init(from:)

enum Status: String, Codable {
    case open, fulfilled

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let value = try container.decode(String.self)
        switch value {
        case "Open":
            self = .open
        case "Fulfilled":
            self = .fulfilled
        default:
            // throw an error or use fatalError()
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I never thought to directly assign them 🙈 thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.