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

Classes conforming to Codable need to synthesize overrides instead of inheriting conformance

    XMLWordPrintable

    Details

      Description

      Classes which inherit from superclasses conforming to Encodable or Decodable should not inherit their superclass's implementations in most cases:

      class A1 : Encodable {
          // Derives Encodable automatically
          let name: String
          init(name: String) { self.name = name }
      }
      
      class B1 : A1 {
          // Silently inherits A1's encode(to:); encodes just {"name": ...}, with no email.
          // This is bad.
          let email: String
          init(name: String, email: String) { self.email = email; super.init(name: name) }
      }
      
      class A2 : Codable {
          // Derives Codable automatically
          let name: String
          init(name: String) { self.name = name }
      }
      
      // Inherits A2's methods. This is correct.
      class B2 : A2 {}
      
      class C2 : A2 {
          // Error: since init(from:) is required, C2 must provide one.
          // It doesn't though, so we get a diagnostic — this is wrong; we should derive in this case.
          let email: String
          init(name: String, email: String) { self.email = email; super.init(name: name) }
      }
      

      Really, the only case where we want to inherit conformance instead of derive is when the class does not add any valid Encodable/Decodable properties.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                itaiferber Itai Ferber
                Reporter:
                itaiferber Itai Ferber
              • Votes:
                2 Vote for this issue
                Watchers:
                6 Start watching this issue

                Dates

                • Created:
                  Updated: