I'm trying to make a List of favorite newspapers. In edit mode the list displays all available newspapers from which the user can select his favorites. After selecting favorites the list displays only the favorites. Here is my code:
struct Newspaper: Hashable {
let name: String
}
struct ContentView: View {
@State var editMode: EditMode = .inactive
@State private var selection = Set<Newspaper>()
var favorites: [Newspaper] {
selection.sorted(by: ({ $0.name < $1.name }))
}
let newspapers = [
Newspaper(name: "New York Times"),
Newspaper(name: "Washington Post")
]
var body: some View {
NavigationView {
List(editMode == .inactive ? favorites : newspapers, id: \.name, selection: $selection) { aliasItem in
Text(aliasItem.name)
}
.toolbar {
EditButton()
}
.environment(\.editMode, self.$editMode)
}
}
}
The problem is that the list enters edit mode, but the selection widgets don't appear. If I replace Newspaper
with just an array of String
(and modify the rest of the code accordingly), then the selection widgets do appear and the list works as expected. Can anyone explain what the problem is?
I originally tried using an Identifiable
Newspaper like this:
struct Newspaper: Codable, Identifiable, Equatable, Hashable {
var id: String { alias + publicationName }
let alias: String
let publicationName: String
}
Since this didn't work, I tested the simpler version above to try to pinpoint the problem.
Since I need to save the favorites, the Newspaper has to be Codable and thus can't use UUID as they are read from disk and the complete Newspapers array is fetched from a server. That's why I have the id
as a computed property.
Yrb:s answer provided the solution to the problem: the type of the selection Set has to be the same type as the id
you are using in your Identifiable
struct and not the type that you are displaying in the List
.
So in my case (with the Identifiable
Newspaper version) the selection Set has to be of type Set<String>
and not Set<Newspaper>
since the id
of Newspaper is a String
.
id
. Do you know why the originalIdentifiable
Newspaper did not work in the List? – Grewitz