Uploaded image for project: 'Swift'
  1. Swift
  2. SR-10237

Codable: Unexpected behavior supplying default value for nullable field

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler
    • Labels:
    • Environment:

      Swift 5

      Description

      Given a JSON object with a nullable field, such as

      {
        "count": null //may be string or null
      }
      

      If you try to decode it into this struct

      struct Sample: Decodable {
        var count: String = "0" //let's default to 0 if null
      }
      

      You'll get the error

      valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "count", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))
      

      I expected no error, and count would be the value if non-null, otherwise "0".

      I actually first tried defining count as a let, which worked without error, but this introduced a bug because it will always be that "default" value even when count is non-null.

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              joey Jordan Hipwell
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated: