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

Default property values in Codable conforming class take precedence when decoding JSON with those properties set

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Invalid
    • Component/s: Compiler
    • Labels:
    • Environment:

      Description

      Decoding JSON with JSONDecoder into a Codable conforming class with properties with default values doesn't work as expected. If the JSON has those properties set with a value, this value gets ignored and the default value of the property gets set.

       

      For example, lets say I have this class:

      public class Example: Codable {

          public let name: String = ""

      }

       

      And this JSON inside a Data property called data:

      {name: "Some Name"}

       

      When doing the following, the 'name' property has a value of "" and not "Some Name".

      let example = try? JSONDecoder().decode(Example.self, from: data)

       

      If I remove the default value and move it into an initializer, decoding works as expected and the 'name' property ends up with a value of "Some Name":

      public class Example: Codable {
      public let name: String
         init()

      { name = "" }

      }

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              georgealegre George Alegre
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: