6

我有一个符合协议EmailVerificationStatus的关联类型的枚举:StringCodable

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

我正在使用的 Web 服务以大写字母 ( UNVERIFIED/ VERIFIED) 发送这些情况。我如何使用CodingKeys枚举来映射这种差异?像下面这样的东西不起作用:

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

3 回答 3

6

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

enum EmailVerificationStatus: String, Codable {
    case verified = "VERIFIED"
    case unverified = "UNVERIFIED"
}
于 2017-09-03T14:06:47.747 回答
0

我建议您使用 struct 作为 Email... 类型并将枚举 CodingKeys 嵌套在您的结构中。CodingKeys 允许您将结构变量与源数据案例(来自 web 服务)进行映射。

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

        enum CodingKeys: String, CodingKey {
            case unverified = "UNVERIFIED"
            case verified = "VERIFIED"
        }
    }
于 2017-10-31T17:11:58.297 回答
0

我通常是这样做的:

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

    enum CodingKeys: String, CodingKey {
        case unverified = "UNVERIFIED"
        case verified = "VERIFIED"
    }
}
于 2020-02-07T04:45:06.750 回答