【发布时间】:2019-02-26 08:32:13
【问题描述】:
我有一个带有字段类型ID的类(枚举类),两者都是可编码的,我无法读取枚举的原始值,我应该实现其他什么
我的代码:
struct Answer: Codable {
let id: ID?
let message: String?
enum CodingKeys: String, CodingKey {
case id = "Id"
case message = "Message"
}
}
enum ID: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(ID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ID"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
如何读取像这样answer.id?.rawValue的值
在我得到的声音中,id 可以是整数或字符串,因此使用可编码类 swift 自动知道实例是好的枚举。
所以,如果我收到我想要的 int:
answer.id?.rawValue
//output 4
所以如果我收到我想要的字符串:
answer.id?.rawValue
//output "male"
当我打印这个时,我注意到它与一个值相关联:
print(answer.id.debugDescription)
//Output: Optional(fitto.ID.integer(2)) or if is string Optional(fitto.ID.string("female"))
【问题讨论】:
-
这个枚举没有原始值,它有关联值。
-
查看docs.swift.org/swift-book/LanguageGuide/Enumerations.html中的示例代码:"您可以使用switch语句检查不同的条形码类型......但是,这一次,关联的值被提取为switch的一部分声明。”
-
感谢马丁的工作