![](/img/trans.png)
[英]Swift 4: how to implement codable protocol for json array of different types
[英]How can I handle different types of JSON data with Codable?
struct Sample: Codable {
let dataA: Info?
enum CodingKeys: String, CodingKey {
case dataA
}
enum Info: Codable {
case double(Double)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Double.self) {
self = .double(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(Info.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Info"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .double(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
}
因此,我从服务器获得了一些数据,如 JSON 并转换为我的 model“样本”。
如您所见, Sample.data
可以是String
或Double
。
但我不知道如何在其他dataA
中获取 dataA。
let foodRate = dataFromServer.dataA
.....?
使用dataA
应该怎么做?
您可以使用switch
语句来提取值
switch dataFromServer.dataA {
case .double(let number):
print(number)
case .string(let string):
print(string)
case .none:
print("Empty")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.