Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update data in SwiftData

I am trying to update data in SwiftData. The documentation, however, is literally just:

func update(expressions: [String : NSExpression], 
    model: any PersistentModel.Type,
    where predicate: NSPredicate? = nil) throws -> Bool

As a new developer, I have no clue what most of this means or how to use it. My code is below:

try? context.update(expressions ["teamScores":NSExpression(format: "\(teamScores)")], model: CounterModel.self)

It failed with exception of type NSException.

I haven't been able to try much, honestly. With such a new framework having literally been released 6 days ago as of writing this, there isn't much documentation or examples outside of setting up the model, persisting data, and querying the database.

like image 535
PaytonDEV Avatar asked Aug 30 '26 23:08

PaytonDEV


1 Answers

To update data in SwiftData, we don't need to touch the modelContext directly. We just need to update the instance and the data would be updated automatically.

Here's an example with simple add list project and keep list tracked when didTapped:

@Model final class AnyItem {
    var name: String
    var didTapped: Bool = false
    init(name: String) {
        self.name = name
    }
}

struct ContentView: View {
    @State var itemName: String = ""
    @Environment(\.modelContext) private var modelContext
    @Query var items: [AnyItem]
    
    var body: some View {
        NavigationStack {
            List {
                Section {
                    TextField("Item name", text: $itemName)
                    Button("Submit", action: addItem)
                }
                
                ForEach(items) { item in
                    Section {
                        Text(item.name)
                        Text("Did tapped: \(item.didTapped.description)")
                    }
                    .onTapGesture {
                        updateItem(item)
                    }
                }
            }
        }
    }
    
    private func addItem() {
        withAnimation {
            let newItem = AnyItem(name: itemName)
            modelContext.insert(newItem)
            itemName = ""
        }
    }
    
    private func updateItem(_ item: AnyItem) {
        withAnimation {
            item.didTapped = true
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: AnyItem.self, inMemory: true)
}
like image 119
Pengguna Avatar answered Sep 03 '26 22:09

Pengguna