Skip to content

[SR-4772] Classes conforming to Codable need to synthesize overrides instead of inheriting conformance #47349

@itaiferber

Description

@itaiferber
Previous ID SR-4772
Radar rdar://problem/31919734
Original Reporter @itaiferber
Type Bug
Additional Detail from JIRA
Votes 2
Component/s Compiler
Labels Bug, DerivedConformance
Assignee @itaiferber
Priority Medium

md5: 9f437e13a1f41076d594d332117a57db

is duplicated by:

  • SR-5431 JSON does not Encode/Decode subclass properties
  • SR-5125 Encodable not decoding properties with subclasses

Issue 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.

Metadata

Metadata

Assignees

Labels

bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfderived conformancesFeature → protocol → conformances: derived conformances aka synthesized conformances

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions