title: How to convert a date string with optional fractional seconds using Codable in Swift?
body: <p>I am replacing my old JSON parsing code with Swift's Codable and am running into a bit of a snag. I guess it isn't as much a Codable question as it is a DateFormatter question.</p>
  
  <p><strong>Start with a struct</strong></p>
  
  <pre><code> struct JustADate: Codable {
      var date: Date
   }
  </code></pre>
  
  <p><strong>and a json string</strong></p>
  
  <pre><code>let json = """
    { "date": "2017-06-19T18:43:19Z" }
  """
  </code></pre>
  
  <p><strong>now lets decode</strong></p>
  
  <pre><code>let decoder = JSONDecoder()
  decoder.dateDecodingStrategy = .iso8601
  
  let data = json.data(using: .utf8)!
  let justADate = try! decoder.decode(JustADate.self, from: data) //all good
  </code></pre>
  
  <p>But if we change the date so that it has fractional seconds, for example:</p>
  
  <pre><code>let json = """
    { "date": "2017-06-19T18:43:19.532Z" }
  """
  </code></pre>
  
  <p>Now it breaks. The dates sometimes come back with fractional seconds and sometimes do not. The way I used to solve it was in my mapping code I had a transform function that tried both dateFormats with and without the fractional seconds. I am not quite sure how to approach it using Codable however. Any suggestions?</p>