7

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 Answers 4

11

Ok. That was simple. No CodingKeys needed:

enum EmailVerificationStatus: String, Codable {
    case verified = "VERIFIED"
    case unverified = "UNVERIFIED"
}
1
  • I've been using Codables since they were introduced, but ran into this problem, too, and I can't believe I didn't think of this. I've been beating my head on the wall for a couple hours.
    – NRitH
    Apr 8, 2020 at 1:15
1

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.