How to use CodingKeys for enums conforming to Codable Protocol?
Asked Answered
E

4

9

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"
}
Escrow answered 3/9, 2017 at 14:1 Comment(0)
E
13

Ok. That was simple. No CodingKeys needed:

enum EmailVerificationStatus: String, Codable {
    case verified = "VERIFIED"
    case unverified = "UNVERIFIED"
}
Escrow answered 3/9, 2017 at 14:6 Comment(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.Amara
P
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"
    }
}
Phantom answered 7/2, 2020 at 4:45 Comment(0)
A
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"
        }
    }
Absa answered 31/10, 2017 at 17:11 Comment(0)
A
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"
  }
}
Alfrediaalfredo answered 23/1, 2023 at 15:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.