title: Decode a nested object in Swift 5 with custom initializer
body: <p>I have an API which returns a payload like this (just one item is included in the example).</p>
  <pre class="lang-json prettyprint-override"><code>{
    &quot;length&quot;: 1,
    &quot;maxPageLimit&quot;: 2500,
    &quot;totalRecords&quot;: 1,
    &quot;data&quot;: [
      {
        &quot;date&quot;: &quot;2021-05-28&quot;,
        &quot;peopleCount&quot;: 412
      }
    ]
  }
  </code></pre>
  <p>I know I can actually create a struct like</p>
  <pre class="lang-swift prettyprint-override"><code>struct Root: Decodable {
    let data: [DailyCount]
  }
  
  struct DailyCount: Decodable {
    let date: String
    let peopleCount: Int
  }
  </code></pre>
  <p>For different calls, the same API returns the same format for the root, but the data is then different. Moreover, I do not need the root info (<code>length</code>, <code>totalRecords</code>, <code>maxPageLimit</code>).
  So, I am considering to create a custom init in <code>struct DailyCount</code> so that I can use it in my URL session</p>
  <pre class="lang-swift prettyprint-override"><code>let reports = try! JSONDecoder().decode([DailyCount].self, from: data!)
  </code></pre>
  <p>Using Swift 5 I tried this:</p>
  <pre class="lang-swift prettyprint-override"><code>struct DailyCount: Decodable {
    let date: String
    let peopleCount: Int
  }
  
  extension DailyCount {
    enum CodingKeys: String, CodingKey {
      case data
      enum DailyCountCodingKeys: String, CodingKey {
        case date
        case peopleCount
      }
    }
    init(from decoder: Decoder) throws {
      // This should let me access the `data` container
      let container = try decoder.container(keyedBy: CodingKeys.self
      peopleCount = try container.decode(Int.self, forKey: . peopleCount)
      date = try container.decode(String.self, forKey: .date)
    }
  }
  </code></pre>
  <p>Unfortunately, it does not work. I get two problems:</p>
  <ol>
  <li>The struct seems not to conform anymore to the <code>Decodable</code> protocol</li>
  <li>The <code>CodingKeys</code> does not contain the <code>peopleCount</code> (therefore returns an error)</li>
  </ol>