I am using swiftui to create a list and using .onMove to move items. I want to update the db information stored in sqlite when moving items. I am using the stephencelis/SQLite.swift library for sqlite.
I have created the code as below. But the code below updates the entire list after the item is moved. Is this method efficient? Or is there another way? For example, updating the moved item and the item to the destination.
Can I get a better code that updates the db of sqlite when moving items in the list? Thank you.
@State private var listItem = [Item]()
ForEach(listItem) { item in
ListCell(
item: item,
onDelete: { deleteItem(item) }
)
}
.onMove(perform: moveItem)
func moveItem(from source : IndexSet, to destination : Int)
{
var tempDataSet : [Item] = listItem
listItem.move(fromOffsets : source, toOffset : destination)
for (index, item) in listItem.enumerated()
{
dbManager.updateDbData(listItem[index].date, listItem[index].content, listItem[index].amount, tempDataSet[index].id)
}
listItem = dbManager.loadDbData()
}
func updateDbData(_ date : String, _ content : String, _ amount : String, _ id : Int)
{
do
{
let update = MainTable.filter(dbId == id)
try db.run(update.update(dbContent < -content, dbDate < -date, dbAmount < -amount))
}
catch (let err)
{
print("updateDbData err = \(err)")
}
}