title: Swift Codable Decode Manually Optional Variable
body: <p>I have the following code:</p>
  
  <pre><code>import Foundation
  
  let jsonData = """
  [
      {"firstname": "Tom", "lastname": "Smith", "age": "28"},
      {"firstname": "Bob", "lastname": "Smith"}
  ]
  """.data(using: .utf8)!
  
  struct Person: Codable {
      let firstName, lastName: String
      let age: String?
  
      enum CodingKeys : String, CodingKey {
          case firstName = "firstname"
          case lastName = "lastname"
          case age
      }
  
      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.decode(String.self, forKey: .age)
      }
  
  }
  
  let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
  print(decoded)
  </code></pre>
  
  <p>Problem is it's crashing on <code>age = try values.decode(String.self, forKey: .age)</code>. When I take that <code>init</code> function out it works fine. The error is <code>No value associated with key age (\"age\").</code>.</p>
  
  <p>Any ideas on how to make that optional and not have it crash when it doesn't exist? I also need that <code>init</code> function for other reasons, but just made a simple example to explain what is going on.</p>