Sorry for the elementary question. In the following case in SwiftData, can I display the results of the search and replace text = "Test" with text = "Test2"?
// Serch
let test = #Predicate<GroupItem> { testitem in
testitem.text.contains("Test")
}
I'm having trouble understanding the database because I can't replace the data that I searched for to see if the search was successful or not.
@Model
class Item {
var id: Int
var groupItem: [GroupItem]?
init(id: Int) {
self.id = id
}
}
@Model
class GroupItem {
var groupId: Int
var text: String
init(groupId: Int, text:String) {
self.groupId = groupId
self.text = text
}
}
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.id)")
} label: {
Text("\(item.id)")
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
ToolbarItem {
Button(action: serchItems) {
Text("Serch")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(id: 0 + 1)
let newItem2 = GroupItem(groupId: 0 + 1, text: "Test")
modelContext.insert(newItem)
modelContext.insert(newItem2)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
private func serchItems() {
// Serch
let test = #Predicate<GroupItem> { testitem in
testitem.text.contains("Test")
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
.modelContainer(for: GroupItem.self, inMemory: true)
}