Does code at 04:41 compile?

The code for @State doesn't seem to work.

struct DonutListView: View {
var donutList: DonutList
@State private var donutToAdd: Donut?
var body: some View {
List(donutList.donuts) { DonutView(donut: $0) }
Button("Add Donut") { donutToAdd = Donut() }
.sheet(item: $donutToAdd) { // <-- would need a "donut in"
TextField("Name", text: $donutToAdd.name) // <-- donutToAdd is optional and I'm not sure how it would be unwrapped
Button("Save") {
donutList.donuts.append(donutToAdd)
donutToAdd = nil
}
Button("Cancel") { donutToAdd = nil }
}
}
}

Does anyone have a fix for this?

Thanks, Dan!

I wish Apple would test their code before presenting at a conference.
I added a name state variable for the TextField.

@State private var name: String = ""
...
.sheet(item: $donutToAdd) { _ in
TextField("Name", text: $name)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(Color.black)
)
Button("Save") {
if let donutToAdd {
donutToAdd.name = name
donutList.donuts.append(donutToAdd )
self.donutToAdd = nil
self.name = ""
}
}
Button("Cancel") { self.donutToAdd = nil }
}
code-block

And DonutList needs to be a class (else you get a mutating member on immutable value).

@Observable
class DonutList {
var donuts: [Donut]
init(donuts: [Donut]) {
self.donuts = donuts
}
}
code-block
Does code at 04:41 compile?
 
 
Q