TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Update JSON with new data

Forums > Swift

Hey all,

I'm currently in day 61 of 100 Days of SwiftUI, and wanted to put some of the knowledge into creating a watchlist app that displays a list of episodes of a series and shows whether you've watched an episode or not.

My goal is to be able to mark an episode as watched, ultimately toggling a watched bool property for any given episode object.

I've created an Episode struct:

struct Episode: Codable, Hashable {
    let episode: String
    let title: String
    let isFiller: Bool
    var watched: Bool
}

Mapped to an array of JSON objects:

[
    {
        "episode": "1",
        "title": "Homecoming",
        "isFiller": false,
        "watched": false
    },
    {
        "episode": "2",
        "title": "The Akatsuki Makes Its Move",
        "isFiller": false,
        "watched": false
    },
    {
        "episode": "3",
        "title": "The Results of Training",
        "isFiller": false,
        "watched": false
    }
]

I'm decoding the JSON file in my ContentView with Paul's handy Bundle extension.

let episodes = Bundle.main.decode([Episode].self, from: "episodesData.json")

And within an EpisodeView for each episode of the list, I'd like to display a Button that allows the user to mark the episode as watched. Here's what I have so far:

Button(episode.watched ? "Mark as unwatched" : "Mark as watched") {
    // Should I be doing this?
    var episodeStruct = Episode(episode: episode.episode,
                                title: episode.title, isFiller: episode.isFiller,
                                watched: episode.watched)

    // Set watched value to watched in this case
    episodeStruct.watched.toggle()

    // How to append this new data to JSON instead of the one I have now that I want to update?

    print("Watched")
}

I've tried to decipher this on my own by reviewing this forum thread, but I can't figure it out as the JSON structure is somewhat different and I'm still not too well-versed with this topic.

Would appreciate any help/explanation 🙏

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.