我有一个EmailVerificationStatus
枚举,其关联类型String
符合Codable
协议:
enum EmailVerificationStatus: String, Codable {
case unverified
case verified
}
我正在使用的网络服务以大写形式发送这些案例(UNVERIFIED
/ VERIFIED
)。如何使用CodingKeys
枚举来映射这种差异?像下面这样的东西不起作用:
enum CodingKeys: String, CodingKey {
case unverified = "UNVERIFIED"
case verified = "VERIFIED"
}
答案 0 :(得分:3)
确定。这很简单。不需要CodingKeys
:
enum EmailVerificationStatus: String, Codable {
case verified = "VERIFIED"
case unverified = "UNVERIFIED"
}
答案 1 :(得分:0)
我建议你使用struct for the email ...类型并将enum CodingKeys嵌套在你的struct中。 CodingKeys允许您使用源数据案例(来自webservice)映射结构变量。
struct EmailVerificationStatus: String, Codable {
var unverified: String
var verified: String
enum CodingKeys: String, CodingKey {
case unverified = "UNVERIFIED"
case verified = "VERIFIED"
}
}
答案 2 :(得分:0)
这是我通常的做法:
struct EmailVerificationStatus: String, Codable {
var unverified: String
var verified: String
enum CodingKeys: String, CodingKey {
case unverified = "UNVERIFIED"
case verified = "VERIFIED"
}
}