I have a simple code (I'm a beginner).
In the code below, row selection is not working. A single row is selected and unselected immediately, multiple rows or doubleclick ends with an error:
CoreDataTable[52390:1238512] Fatal error: Duplicate elements of type 'Optional' were found in a Set.
This usually means either that the type violates Hashable's requirements, or
that members of such a set were mutated after insertion.
Single line selection (@State private var selection:Item.ID) works correctly.
What am I doing wrong? Thanks for any advice.
Ludek.
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
@State private var selection = Set<Item.ID>()
var body: some View {
Table(items, selection: $selection) {
TableColumn("Name") {
Text($0.name ?? "NoName")
}
}
.padding()
.toolbar {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
let count = items.count + 1
newItem.id = UUID()
newItem.name = "Test nr.: \(count)"
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}