How to use selection in List in SwiftUI

Issue #745

I used to use selection with Binding where wrappedValue is optional, together with tag in SwiftUI for macOS, and it shows current selection

1
2
3
4
5
6
7
@Binding
var selection: Tag? = .all

List(section: $selection) {
Text("All")
.tag(Tag.all)
}

From the API, looks like Binding<Set> is for multiple selection, and Binding<Optional> is for single selection
Looking at List signature, I see that selection uses wrappedValue as Set for Binding<Set<SelectionValue>>?

1
init<Data, ID, RowContent>(Data, id: KeyPath<Data.Element, ID>, selection: Binding<Set<SelectionValue>>?, rowContent: (Data.Element) -> RowContent)

So let’s use Set. It shows current selection and I don’t need to use .tag also

let selection: Binding<Set<SidebarTag>> = Binding<Set<SidebarTag>>(
    get: { Set(arrayLiteral: store.sidebarTag) },
    set: { newValue in
        DispatchQueue.main.async {
            if let first = newValue.first {
                store.sidebarTag = first
            }
        }
    }
)

List(selection: selection) {
    Text("All")
}

Updated at 2021-01-06 21:13:43

Comments