-2

I have some codable struct and I'd like to create a [String:Any] dictionary from it to iterate over its properties. I created a computed property:

var dictionary: [String: Any] {
    return (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self), options: [])) as? [String: Any] ?? [:]
}

When I iterate over the dictionary and try to cast 'Any', types like 'Data' and 'Date' never work. Casting works only for 'String', 'Int' and 'Double'. Is it possible to cast the 'Data' and 'Date' somehow? Thank you in advance.

Alexey Chekanov
  • 1,047
  • 14
  • 25
  • If you have type-specific structs why do want to convert them to unspecified Dictionary? `Data` and `Date` don't work, because JSON doesn't support them. You could use `PropertyListEncoder` which supports `Date` and `Data` – vadian Dec 23 '17 at 20:10

1 Answers1

1

JSON has no predefined or standard encoding for dates or byte sequences (data).

Both JSONEncoder and JSONDecoder have properties dateEncodingStrategy and dataEncodingStrategy you can set to match whatever format you're using in your JSON.

Gereon
  • 17,258
  • 4
  • 42
  • 73
  • This is correct. The frustrating part is figuring out how to set up your date formatting string. I recommend going into the Playground to get it working, and use this reference: [Unicode Date Formats for OS X 10.9 and iOS 7+](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns). – CommaToast Dec 23 '17 at 20:48
  • @CommaToast https://stackoverflow.com/questions/46458487/how-to-convert-a-date-string-with-optional-fractional-seconds-using-codable-in-s/46458771?s=4|0.0000#46458771 – Leo Dabus Dec 23 '17 at 20:54