Reputation: 898
In SwiftUI I want to show the favourite items only and I'm trying to do this with an if statement within the ForEach-element. See the code:
var body: some View {
NavigationView {
List {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorites only")
}
ForEach(self.buildings, id: \.self) { building in
if(!self.showFavoritesOnly || building.favourite) {
Text("Blah")
}
}
}
}
}
However I getting a 'Unable to infer complex closure return type; add explicit type to disambiguate' error.
How can I select an item conditionally in a ForEach element?
Upvotes: 0
Views: 737
Reputation: 898
Using a filter is a working solution
var body: some View {
NavigationView {
List {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorites only")
}
ForEach(self.buildings.filter({b in self.showFavoritesOnly || b.favourite}), id: \.self) { building in
Text("Blah")
}
}
}
Still, I wonder how could I have fixed it using an if-statement
Upvotes: 2