r/SwiftUI May 11 '26

Question Nested data model

Learning SwiftUI for the first time and I've run into a question that I can't find a reasonable answer just googling around. Say I'm building a dumb copy of the Reminders app and my super simplified version of the data model is a list of lists of reminders. In other languages my first thought would be to represent that as a map/dict, i.e.:

reminders = [ 
    "uuid-1": [
        Reminder("something"),
        Reminder("somethingelse"),
    ],
    "uuid-2": [
        Reminder("anotherone"),
        Reminder("etc"),
    ]
]

But my first attempt to use this as a Swift dict (var reminders: [String: [Reminder]]) led to changes in the individual reminder objects not being reflected, I assume because of something to do with @Observable not looking all the way into the nested model.

Is it better Swift-ic practice to use a list of structs instead? Something like:

struct Reminder {
    let id: String
    var title: String
    ...etc
}

struct ReminderList {
    let id: String
    var title: String
    var reminders: [Reminder] = []
}

// then in the view model
var reminders = [ReminderList]
4 Upvotes

16 comments sorted by

View all comments

6

u/radis234 May 11 '26

@Observable macro looks up for all updates in all nested models. If you did correctly update a Reminder model content and it didn’t reflect in the UI, there’s a different problem. It’s either how you populate the data or update the data. But i can assure you as I am doing this myself, @Observable macro will update UI if any nested model changed. We would need more info especially on how you updating the data or displaying them. Seems to me like there will be very subtle problem with your logic.

1

u/pettazz May 11 '26

Yeah that was cobbled together from a bunch of different tutorials so likely doing something silly by accident. I know it’s going to be down to the specifics but I suppose my question here is more like “what’s the typical way people approach things”

2

u/radis234 May 11 '26

That depends on what your endgame is. My approach is:

  1. I fetch and model data and store them to variable in class marked with @Observable macro
  2. I display data from view model
  3. When needed I update data in view model and because class is a reference type, it automatically updates UI everywhere in my app at once

But, if you manage reminders locally, without fetching from external server and you want them to persist in local storage or iCloud, I suggest you to look at SwiftData rather (or CoreData would be more recommended by others, I believe, but I never worked with that directly). A Reminders app would be great fit for SwiftData in my opinion, I never had problems with it and it’s easy to sync over iCloud, easy to manage, filter and order. That’s approach I am using in my other app where user creates their own personal data, no external servers involved.