作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 Codable
结构 myObj
:
public struct VIO: Codable {
let id:Int?;
...
var par1:Bool = false; //default to avoid error in parsing
var par2:Bool = false;
}
当我收到 JSON 时,我没有 par1
和 par2
,因为这些变量是可选的。解析过程中出现错误: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
}
编辑:
如果 par1
和 par2
也应该被解码,则您必须编写自定义初始化程序
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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!