To write to a JSON file in Swift, first you need to create a struct or class that conforms to the Codable protocol. This struct or class represents the structure of your JSON data. Then, you need to encode the data into a JSON format using the JSONEncoder. Finally, you need to write the data to the file system using the FileManager.
Here's an example:
main.swift628 chars24 lines
In this example, I created a Person struct that conforms to the Codable protocol. I then created an instance of Person and encoded it to a JSON format using the JSONEncoder. I also set the outputFormatting property to .prettyPrinted so that the JSON data is formatted nicely for readability.
Next, I created a FileManager instance to get the path to the user's documents directory. I then appended the file name "person.json" to the path and created a URL for the file. Finally, I wrote the encoded JSON data to the file using the write method of the String class. I also added error handling to catch any exceptions that may be thrown during the file writing process.
Note that this is a simple example and error handling can be improved depending on your use case.
gistlibby LogSnag