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.

Peter Liaw
  • 961
  • 1
  • 7
  • 6
  • This works fine when I run the code in a playground, b2 is Optional(true). – Joakim Danielson Feb 22 '22 at 07:54
  • I tested in Playground, and I got `b2: Optional(true)`, so maybe your real test/code/sample is wrong, not this one... – Larme Feb 22 '22 at 07:54
  • 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? – Peter Liaw Feb 22 '22 at 18:12

1 Answers1

6

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.

Peter Liaw
  • 961
  • 1
  • 7
  • 6