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

Decodable: type mismatch error when decoding string to date as dictionary key

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: Foundation
    • Labels:
    • Environment:

      MacPro 5.1 16 GB RAM

      macOS 10.13.6

      Xcode 10.1 (10B61)

      Description

      If you are going to decode a string to date with the .formatted date decoding strategy as dictionary key you get a type mismatch error about an expected array:

      typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "bar", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

      Code:

       

       

      let json = """
      {"bar": { "2019-02-20": 100.10 }}
      """
      struct Foo: Decodable {
          let bar: [Date: Double]
      }
       
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "yyyy-MM-dd"
      dateFormatter.locale = Locale(identifier: "en_US_POSIX")
      let decoder = JSONDecoder()
      decoder.dateDecodingStrategy = .formatted(dateFormatter)
      let data = Data(json.utf8)
      do {
          let decoded = try decoder.decode(Foo.self, from: data)
          print(decoded)
      } catch {
          print(error)
      }
      

       

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                bendjones Ben D. Jones
                Reporter:
                vadian Stefan Klieme
              • Votes:
                0 Vote for this issue
                Watchers:
                4 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: