使用编码键从解码中排除值



我有以下结构来解码JSON数据:

更新:

struct Section {
let owner : String
var items : [ValueVariables]
}
struct ValueVariables : Decodable {
var isSelected = false
let breed: String
let color: String
let tagNum: Int
// other members 
}

问题是isSelected不是正在解码的值,我如何从解码中排除它以防止它导致如下错误:

keyNotFound(CodingKeys(stringValue: "isSelected", intValue: nil(, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0(], debugDescription: "没有与键关联的值 CodingKeys(stringValue: \"isSelected\", intValue: nil( (\"isSelected\"(,转换为 is_selected.",底层错误:nil((

我尝试过使用这样的编码键,但它似乎不起作用:

private enum CodingKeys : String, CodingKey {
case isSelected = "isSelected"
}

应用答案:

struct ValueVariables : Decodable {
private enum CodingKeys : String, CodingKey {
case breed, color, tagNum
}
var isSelected = false
let breed: String
let color: String
let tagNum: Int
}

JSON看起来像这样:

[{"breed":"dog","color":"black","tagNum":20394}]

收到的错误:

类型"值变量"不符合协议"可解码">

相反,您必须指定所有要解码的键。

struct ValueVariables : Decodable {
private enum CodingKeys : String, CodingKey {
case breed, color
}
var isSelected = false
let breed: String
let color: String
}

最新更新