Swift JSONDecoder doesn't handle optional Bool as expected

Viewed 374

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.

1 Answers

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.

Related