0

I'm working on a document-based SwiftUI application, and my file contents includes large arrays of doubles. The application involves importing some data from CSV, and then the file saves this data in a data structure.

However, when looking at the file sizes, the custom document type I declare in my application is 2-3 times larger than the CSV file. The other bits of metadata could not possibly be that large.

Here's the JSON output that is saved to file:

JSON output saved to file

Here's the CSV file that was imported:

original CSV file

On looking at the raw text of the JSON output and comparing it with the original CSV, it became obvious that the file format I declare was using a lot of unnecessary precision. How do I make Swift's JSONEncoder only use, for example, 4 decimal places of precision?

jnpdx
  • 45,847
  • 6
  • 64
  • 94
Tahmid Azam
  • 566
  • 4
  • 16
  • You could use `Decimal` instead of `Double` as the data type, or use a custom encode. `JSONEncoder` has no option for precision. – burnsi Jan 02 '23 at 19:01
  • Or use strings in your json – Joakim Danielson Jan 02 '23 at 20:52
  • You could customize the encoding behaviour using a property wrapper. Every time you write a double to the property, you could have it round in a way that shorts it’s decimal representation. Not sure about how to do that exactly, though – Alexander Jan 06 '23 at 17:05

0 Answers0