Pet*_*iaw 6 boolean swift jsondecoder
在下面的程序中,我定义了一个包含 Bool、String 和 Int 的结构体,包括非可选版本和选项版本。当我运行它时,可选的 String 和 Int 按预期解码 json 数据,但 b2 永远不会解析 json 中的值,并且始终为 nil,即使 b2 存在于 json 中也是如此。
struct ResponseData: Decodable {
let b1: Bool
let b2: Bool?
let s1: String
let s2: String?
let i1: Int
let i2: Int?
}
let json = """
{"b1": true,
"b2": true,
"s1": "abc",
"s2": "ccdb",
"i1": 1,
"i2": 2,
}
"""
let decoder = JSONDecoder()
let data = json.data(using: .utf8)!
guard let obj = try? decoder.decode(ResponseData.self, from: data) else {
return
}
print(obj)
// RESULTS
// b1: true
// b2: nil (why is this not "true"?)
// s1: "abc"
// s2: "ccdb"
// i1: 1
// i2: 2
Run Code Online (Sandbox Code Playgroud)
JSONDecoder 处理可选 Bool 的方式与其他类型的数据不同是否有原因?我想将某些 Bool 定义为可选,因为它们不是必需的,但希望检索定义了它们的值。
| 归档时间: |
|
| 查看次数: |
1303 次 |
| 最近记录: |