Why doesn't this work? (Specifically, it crashes.)
struct Item: Identifiable, Hashable, Codable {
var id = UUID()
var name: String? = nil
}
private let defaults: [Item] = [
Item(name: "Bread"),
Item(),
Item(name: "Peanut Butter"),
Item(name: "Jelly")
]
struct ContentView: View {
@State var selectedItem = Set<Item>()
@State var showSheet = false
var body: some View {
VStack {
ForEach(defaults, id: \.self) { item in
Button(item.name ?? "<unnamed>") {
self.selectedItem.removeAll()
self.selectedItem.insert(item)
print("Selected item is now \(self.selectedItem)")
self.showSheet = true
}
}
}
.sheet(isPresented: self.$showSheet) {
let _ = print("selected item \(self.selectedItem)")
RenameSheet(name: self.selectedItem.first!.name ?? "<no name>") {
self.selectedItem.removeAll()
}
}
.padding()
}
}
Based on the output from the print
s, it gets set when the button is clicked, but is then empty when the sheet is presented.