How to use CodingKeys for enums conforming to Codable Protocol?

2.9k views Asked by At

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"
}
4

There are 4 answers

1
André Slotta On BEST ANSWER

Ok. That was simple. No CodingKeys needed:

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

Another possible solution that is helpful when your enum has associated values is to put the Codable compliance into an extension and then it will not complain about you implementing the CodingKeys enum.

Something like this:

enum EmailVerificationStatus: String {
    case unverified
    case verified(email:String)
}

extension EmailVerificationStatus: Codable {
  enum CodingKeys: String, CodingKey {
    case unverified = "UNVERIFIED"
    case verified = "VERIFIED"
  }
}
0
Tejas On

This is how I usually do it:

struct EmailVerificationStatus: String, Codable {
    var unverified: String
    var verified: String

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

I would suggest you use struct for the Email... type and nest the enum CodingKeys inside your struct. CodingKeys allows you to map your struct variables with your source data cases (from webservice).

struct EmailVerificationStatus: String, Codable {
        var unverified: String
        var verified: String

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