ios 如何将CodingKeys用于符合可编码协议的枚举?

tzxcd3kk  于 2023-02-01  发布在  iOS
关注(0)|答案(4)|浏览(114)

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

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

我正在使用的Web服务以大写形式发送这些情况(UNVERIFIED/VERIFIED)。如何使用CodingKeys枚举来Map这种差异?类似以下内容的内容不起作用:

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

5q4ezhmt1#

好的。很简单。不需要CodingKeys

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

hiz5n14c2#

我通常是这么做的:

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

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

7y4bm7vi3#

我建议你使用struct作为Email...类型,并将枚举CodingKeys嵌套在你的struct中。CodingKeys允许你将你的struct变量Map到你的源数据案例(来自webservice)。

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

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

3pmvbmvn4#

当枚举具有关联值时,另一个可能的解决方案是将Codable兼容性放入扩展中,这样它就不会抱怨您实现了CodingKeys枚举。
大概是这样的

enum EmailVerificationStatus: String {
    case unverified
    case verified(email:String)
}

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

相关问题