In the following program, I have defined a struct with Bool, String and Int, both non-optional and option versions. When I run it, the optional String and Int decodes the json data as expected, but b2 never parses the value from the json, and is always nil, even if b2 is present in the 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
Is there a reason why JSONDecoder handles optional Bool's differently than the other types of data? I want to define certain Bool's as optional because they are not required, but want to retrieve the value if they are defined.
b2: Optional(true)
, so maybe your real test/code/sample is wrong, not this one... – Cucurbitb2: Optional(true)
just like you guys observed!! So is watch window buggy? – Dravidian