ios - 不同类型的 Json 属性
问题描述
我有一个对象,像这样从 json 反序列化。json 属性之一可能具有两种不同的类型(即枚举的原因)
enum CarValues: Codable { // this enum to recognize,what type of value in array we need
case withParam(ValuesWithParam)
case withoutParam(ValuesWithoutParam)
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
switch self {
case .withParam(let v): try container.encode(v)
case .withoutParam(let v): try container.encode(v)
}
}
func returnId() -> Int?{
switch self {
case .withParam(let v):
return v.params[0].id
default :
return nil
}
}
func initValue(value: String){
switch self {
case .withParam (var v):
v.params[0].setValue(valueToAdd: value)
default:
_ = ""
}
}
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
if let v = try? value.decode(ValuesWithParam.self) {
self = .withParam(v)
return
} else if let v = try? value.decode(ValuesWithoutParam.self) {
self = .withoutParam(v)
return
}
throw Values.ParseError.notRecognizedType(value)
}
enum ParseError: Error {
case notRecognizedType(Any)
}
}
struct ValuesWithParam: Decodable, Encodable{
var id: Int
var title: String
var params: [Car]
}
struct ValuesWithoutParam: Decodable, Encodable{
var id: Int
var title: String
}
我想改变这个对象的一些属性,我该怎么做?我尝试在 function 中执行此操作initValue
,但是 (var v) - 只有基本对象的副本。
解决方案
将您的initValue
功能修改为:
mutating func initValue(value: String){
if case .withParam (var v) = self {
v.params[0].setValue(valueToAdd: value)
self = .withParam(v)
}
}
要更新您的enum
值,您必须替换它,并且它需要mutating
功能才能这样做。
另外,我switch
只替换了一个case
用if case
.
推荐阅读
- python - RaspberryPi Shell 在 Python-Curses (Ctrl-C) 后冻结
- javascript - 为什么我的两个值没有正确比较?
- c# - 如何在 C# 中使用按键浏览列表
- python - 使用 Selenium、Python 和 Openpyxl 循环遍历 IP 地址列的问题
- pm2 - 如何让 Jelastic 启动 PM2 以启动“npm”命令而不是文件?
- python - 如何让这个计时器正确倒计时?
- locking - Redshift - 强制执行自动提交
- python - 它继续打印
- mongodb - 如果在bulkWrite期间mongodb中不存在记录,如何创建记录?
- javascript - Javascript - 将带有注释的字符串转换为对象