|
Hello, For some reason, I am unable to add a second item to my custom JSON file. I'm fairly sure I'm missing something elementary, but couldn't figure it out yet.
Above code writes JSON fine, but when I run the function again with a different entry, the only entry gets replaced. Any ideas? |
|
You create an empty Item array each time the function is called. Then you append the one item and only that item to the array. So the array you write to disk will only ever have one item. Depending on your use case you can do several things, but all involve storing the item array with all that items somewhere. Instead of declaring it inside your function, declare it at the top of the file and inside the function append the new item. Then write the array to disk, that will now contain all items! |
|
Thank you for your reply. You're totally right about the array initialization, however, if I declare it outside the function, I still can't get it to work. Below latest playground code:
I tried encoding both entry and the array itself separately, but all I see is just one entry. |
|
hi, at some point, you need to read the items back into the program (you only write data in this program). and i think you want to write all of the Items in the array, not just a single Item. (i.e., your writeJSON function appends an item to the array, but then writes out only the one item appended (not the entire array). this code should work for you: it declares the array of Items with a code block that will be executed the first time you code references the array variable. that code block will load what's out there on disk already.
i'd rewrite the writeJSON function to write out the whole array:
from there, here's some basic code that shows you what's happening
the first time you run this code (and there is no existing file on your desktop), your output will look like this:
the second time you run, all the items from the first run will be there at the start, and you'll then add even more items, producing this output:
hope that helps, DMG |
|
|
|
@bitigchi i used your function to write my json but when i close my app and open it again the code reverts to my original json not the new appended version |
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.