gpt4 book ai didi

Swift 4 JSONDecoder 可选变量

转载 作者:行者123 更新时间:2023-11-28 12:04:22 26 4
gpt4 key购买 nike

我有一个 Codable 结构 myObj:

public struct VIO: Codable {

let id:Int?;
...
var par1:Bool = false; //default to avoid error in parsing
var par2:Bool = false;
}

当我收到 JSON 时,我没有 par1par2,因为这些变量是可选的。解析过程中出现错误:keyNotFound(CodingKeys(stringValue:\"par1\", intValue: nil)

如何解决?

最佳答案

如果您有局部变量,则必须指定 CodingKeys

public struct VIO: Codable {

private enum CodingKeys : String, CodingKey { case id }

let id:Int?
...
var par1:Bool = false
var par2:Bool = false

}

编辑:

如果 par1par2 也应该被解码,则您必须编写自定义初始化程序

  private enum CodingKeys : String, CodingKey { case id, par1, par2 }

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
par1 = try container.decodeIfPresent(Bool.self, forKey: .par1)
par2 = try container.decodeIfPresent(Bool.self, forKey: .par2)
}

这就是 Swift:没有尾随分号

关于Swift 4 JSONDecoder 可选变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com