SwiftUI: @State and sheets

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 prints, it gets set when the button is clicked, but is then empty when the sheet is presented.

Where's the crash? What's RenameSheet look like? Do you need to assign nil in var name: String? = nil?

Use .sheet(item: ...) instead, or capture the variable, like .sheet(isPresented: self.$showSheet) { [selectedItem] in ...}

@workingdogintokyo's suggestion worked. Except the compiler warns that the capture isn't used, even though it is. Yay!

SwiftUI: @State and sheets
 
 
Q