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

Swift 4 Decodable Loses Subclass Type Information

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Invalid
    • Component/s: Standard Library
    • Labels:
      None
    • Environment:

      Swift 4, Xcode 9 (betas 1 and 2), macOS 10.13 (betas 1 and 2).

      Description

      Decoding an Array<Superclass> that contains a heterogenous mix of Superclass and Subclass: Superclass incorrectly infers all members to be of type Superclass, thereby breaking decoding as Subclass.init(from is never called.

      Steps to Reproduce:
      Assuming a class Superclass: Codable and class Subclass: Superclass, where Superclass has a var children: [Superclass], a round trip through an encoder/decoder of any type loses the subclass type information of any Subclass instances in the children array (they are all assumed to be Superclass). This breaks decoding of Subclass because the subclass' overridden init(from is never called since it's incorrectly assumed to be of type Superclass. Demonstration playground attached.

      Expected Results:
      When an encoded Array<Superclass> with heterogenous mix of Superclass and Subclass: Superclass is decoded, I expect the type information to be preserved so that instances of Subclass have their init(from called.

      Observed Results:
      In the attached simplified Playground example, the line:

      let firstDecodedChild = decodedRoot.children.first as? Subclass

      ...evaluates to nil because the as? fails to cast what it assumes to be a Superclass instance to a Subclass. If you remove the as? you get an instance of Superclass.

      In a more complex model with more properties, you get complaints about keys not being found, presumably because the Decoders are not descending into the Subclass instances' "super" containers as it thinks it has everything it needs.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned
              Reporter:
              jnozzi Joshua Nozzi
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: