I have a data model in my SwiftUI app that looks something like this:
struct Entry: Identifiable{
var id = UUID().uuidString
var name = ""
var duration: Int{
//An SQLite query that returns the total of the "duration" column
let total = try! dbc.scalar(tableFlight.filter(db.entry == id).select(db.duration.total))
return Int(total)
}
}
struct Flight: Identifiable{
var id = UUID().uuidString
var duration = 0
var entry: String?
}
I have an ObservableObject
view model that produces the entries like this:
class EntryModel: ObservableObject{
static let shared = EntryModel()
@Published var entries = [Entry]()
init(){
get()
}
func get(){
//Stuff to fetch the entries
entries = //SQLite query that returns an array of Entry objects
}
}
Then finally, in my View
, I list all the entry names and their associated duration
like this:
ForEach(modelEntry.entries){ entry in
VStack{
Text(entry.name) //<-- Updates fine
Text(entry.duration) //<-- Gets set initially, but no updates
}
}
The issue I'm having is that when I update a Flight
for that Entry
, the duration
in my view doesn't update. I know that won't happen because only the entries
will redraw when they are changed.
But even if I manually call the get()
function in my EntryModel
, the associated duration
still doesn't update.
Is there a better way to do this? How do I get the parent's computed properties to recalculate when its child element is updated?