I have a SwiftUI list, defined in a typical fashion:
struct SettingsView: View
{
@State private var selectedCategory: SettingsCategory? = .general
List(SettingsCategory.allCases, id: \.self, selection: $selectedCategory) { category in
[...]
}
}
In this case, the List is a table of "categories" for a settings area in my UI. The SettingsCategory is an enum that defines these categories, and the UI ends up looking like this:
It is not appropriate for this list to have an empty selection; a category should always be selected. In AppKit, it was trivially easy to disable an empty selection on NSTableView. But in SwiftUI, I've been unable to find a way to disable it. Anytime I click in the empty area of the list, the selection is cleared. How can I stop that?
selectedCategory must be an Optional or the compiler vomits all over itself.
I can't use willSet/didSet on selectedCategory because of the @State property wrapper. And I can't use a computed property that never returns nil because the List's selection has to be bound.
I also tried this approach: SwiftUI DatePicker Binding optional Date, valid nil
So, what magical incantation is required to disable empty selection in List?

selectionon aListto work, you have to have theListineditMode. Once the list is ineditModethe initial selection is selected. You can roll your own implementation with List pretty easily, just don't useselection. It isn't meant to be for menus.selectionwas not intended to be a menu picker. In the time it took you to ask this question, you could have rolled your own solution. But, keep trying to make this work, by all means.NSTableViewto power a UI like this has been standard practice on the Mac for quite literally decades. If there’s a better approach thanList, please do share.Listalso comes with lots of freebies that would be tedious to implement manually: the correct selection color based on theNSWindowstate (main/key, background), the automatic coloring of text/icon in selected rows, etc. AndListselections are absolutely appropriate: lots of Mac UI changes based on selections in aList. Think of a simple master/detail UI with an inspector on the right that shows details about the stuff selected in the list.