title: Swift Codable Map Children by ID
body: <p>I have the following code.</p>
  
  <pre><code>import Foundation
  
  let jsonData = """
  [
      {"id": "1", "firstname": "Tom", "lastname": "Smith", "age": "28"},
      {"id": "2", "firstname": "Bob", "lastname": "Smith"},
      {"id": "3", "firstname": "Jim", "lastname": "Smith", "parentid": "2"},
      {"id": "4", "firstname": "Ray", "lastname": "Smith", "parentid": "3"}
  ]
  """.data(using: .utf8)!
  
  class Person: Codable {
      let id: String
      let firstName, lastName: String
      let age: String?
      let parentid: String?
      let children: [Person]?
  
      enum CodingKeys : String, CodingKey {
          case firstName = "firstname"
          case lastName = "lastname"
          case age
          case parentid
          case id
      }
  
      init(from decoder: Decoder) throws {
          let values = try decoder.container(keyedBy: CodingKeys.self)
          firstName = try values.decode(String.self, forKey: .firstName)
          lastName = try values.decode(String.self, forKey: .lastName)
          age = try values.decodeIfPresent(String.self, forKey: .age)
          parentid = try values.decodeIfPresent(String.self, forKey: .parentid)
          id = try values.decodeIfPresent(String.self, forKey: .id)
      }
  
  }
  
  let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
  print(decoded)
  </code></pre>
  
  <p>So I have that <code>children</code> property. I basically want <code>decoded</code> to be an array with 2 <code>Person</code> objects (Tom and Bob). <code>decoded[1].children</code> should be an array with 1 <code>Person</code> object (Jim). And <code>decoded[1].children[0]</code> should be an array with 1 <code>Person</code> object (Ray).</p>
  
  <p>How can I achieve this using the Swift Codable system?</p>