如何将 CodingKeys 用于符合 Codable 协议的枚举?

How to use CodingKeys for enums conforming to Codable Protocol?

我有一个 EmailVerificationStatus 枚举,其关联类型 String 符合 Codable 协议:

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

我正在使用的网络服务以大写形式发送这些案例 (UNVERIFIED / VERIFIED)。我如何使用 CodingKeys 枚举来映射该差异?以下内容不起作用:

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

好的。那很简单。不需要 CodingKeys

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

我建议您对电子邮件使用结构...键入并将枚举 CodingKeys 嵌套在您的结构中。 CodingKeys 允许您将结构变量映射到源数据案例(来自网络服务)。

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

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

我通常是这样做的:

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

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