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

CodingKeys are improperly generated for nested Decodable/Encodable objects

    XMLWordPrintable

    Details

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

      Description

      Referencing the compiler-generated CodingKeys enum within the init of a nested Decodable or Encodable fails. For example:

      struct Outer: Decodable {
        var a: Int
      
        struct Inner: Decodable {
          var b: Int
      
          init(from decoder: Decoder) throws {
            // CodingKeys should be Inner.CodingKeys, but is Outer.CodingKeys
            let container = try decoder.container(keyedBy: CodingKeys.self)
            b = try container.decode(Int.self, forKey: .b) // compiler error
          }
        }
      }

      However, this works perfectly fine for objects conforming to Codable:

      struct Outer: Codable {
        var a: Int
      
        struct Inner: Codable {
          var b: Int
      
          init(from decoder: Decoder) throws {
            // CodingKeys is Inner.CodingKeys
            let container = try decoder.container(keyedBy: CodingKeys.self)
            b = try container.decode(Int.self, forKey: .b)
          }
        }
      }

      When an explicitly-defined CodingKeys enum is provided, everything works as expected:

      struct Outer: Decodable {
        var a: Int
      
        struct Inner: Decodable {
          var b: Int
      
          private enum CodingKeys: CodingKey {
            case b
          }
      
          init(from decoder: Decoder) throws {
            // CodingKeys is Inner.CodingKeys
            let container = try decoder.container(keyedBy: CodingKeys.self)
            b = try container.decode(Int.self, forKey: .b) // works fine
          }
        }
      } 

       

      Possibly related to https://bugs.swift.org/browse/SR-5215

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              jonstaff Jon Staff
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated: