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

Codable decoder issue when inheriting from a Class conforming to Codable

    XMLWordPrintable

    Details

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

      Version 9.2 (9C40b)

      Description

      When a class inherits from a base class that conforms to Codable, the decoding is not executed (more on that below) and the returned object has the default properties values.

      class BaseClass: Codable {}
      
      class MyClass: BaseClass {
      
          enum CodingKeys: String, CodingKey {
              case objectId = "id"
              case name
          }
          
          var objectId: Int = -1
          var name: String = ""
      }
      
      let dataString = "{\"id\":123,\"name\":\"test object\"}"
      let data = dataString.data(using: .utf8)!
      
      do {
          let object = try JSONDecoder().decode(MyClass.self, from: data)
          print(object.objectId) //outputs -1 or BAD_ACCESS (and not 123 as expected)
      }
      catch {
          print(error)
      }
      

       

      But, if I use either:

      protocol Base: Codable { //protocol "base"
      }
      
      class MyClass: BaseClass {
      ...
      }
      

      The decoding is preformed as expected.

       

       

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                itaiferber Itai Ferber
                Reporter:
                barakrl Barak Harel
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated: