I have a simple SwiftUI app with a sidebar and detail pane implement using NavigationSplitView
. It works OK, except when (programmatically) deselecting the item selected in the list, the app crashes with an unhelpful stack trace (mostly ___lldb_unamed_symbol
). Specifically, when selectedItem = nil
, the app crashes.
The issue can be reproduced with the program below:
import SwiftUI
struct Person: Hashable {
var firstName: String
var lastName: String
}
struct PersonDetailView: View {
var body: some View {
if let selectedPersonBinding = Binding($selection) {
VStack {
TextField("First Name", text: selectedPersonBinding.firstName)
TextField("Last Name", text: selectedPersonBinding.lastName)
}
.padding()
}
}
@Binding var selection: Person?
}
struct ContentView: View {
var body: some View {
NavigationSplitView {
List(people, id: .self, selection: $selectedPerson) {
Text($0.firstName)
}
.toolbar {
Button("Deselect") {
selectedPerson = nil
}
}
} detail: {
PersonDetailView(selection: $selectedPerson)
}
.onAppear() {
selectedPerson = people[0]
}
}
let people = [
Person(firstName: "Steve", lastName: "Jobs"),
Person(firstName: "Steve", lastName: "Wozniak"),
Person(firstName: "Ronald", lastName: "Wayne")
]
@State var selectedPerson: Person?
}
Run that on Mac or iPad, click the “Deselect” button, and the app will crash.
I’ve deduced that it has something to do with the detail view’s binding to selectedPerson
, as the problem goes away if I remove that binding, but I can’t figure out why it should crash with that binding there.