Search code examples
iosenumsswift4codable

How to use CodingKeys for enums conforming to Codable Protocol?


I have an EmailVerificationStatus enum with an associated type of String that conforms to the Codable protocol:

enum EmailVerificationStatus: String, Codable {
    case unverified
    case verified
}

The webservice I am working with sends those cases in uppercase (UNVERIFIED / VERIFIED). How can I use the CodingKeys enumeration to map that difference? Something like the following does not work:

enum CodingKeys: String, CodingKey {
    case unverified = "UNVERIFIED"
    case verified = "VERIFIED"
}

Solution

  • Ok. That was simple. No CodingKeys needed:

    enum EmailVerificationStatus: String, Codable {
        case verified = "VERIFIED"
        case unverified = "UNVERIFIED"
    }