Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 539
André Slotta Avatar asked Sep 03 '17 14:09

André Slotta


Video Answer


2 Answers

Ok. That was simple. No CodingKeys needed:

enum EmailVerificationStatus: String, Codable {
    case verified = "VERIFIED"
    case unverified = "UNVERIFIED"
}
like image 165
André Slotta Avatar answered Nov 15 '22 09:11

André Slotta


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"
    }
}
like image 23
Tejas Avatar answered Nov 15 '22 10:11

Tejas