Swift JSONDecoder doesn't handle optional Bool as expected
Asked Answered
D

1

6

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.

Dravidian answered 22/2, 2022 at 7:47 Comment(3)
This works fine when I run the code in a playground, b2 is Optional(true).Airdry
I tested in Playground, and I got b2: Optional(true), so maybe your real test/code/sample is wrong, not this one...Cucurbit
I just realized that in the "Watch" window b2 is nil, but in the output view, it prints b2: Optional(true) just like you guys observed!! So is watch window buggy?Dravidian
D
7

Thanks for your help, guys. I was able to confirm that the "watch" window was showing the wrong value when I placed a breakpoint at the print statement. The actual value of b2 is "true", even though "watch" window indicated nil.

Dravidian answered 22/2, 2022 at 18:34 Comment(1)
What a reliable IDE! Thanks Apple.Apex

© 2022 - 2024 — McMap. All rights reserved.