0

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?

1
  • May be ForEach is asking for the else part as it can not return a nil View if condition does not match. Just a suggestion I am not sure! Commented Oct 14, 2019 at 15:18

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I remember that I have seen the “if” approach in an example from Apple. Of course filtering is much better or even better placing it in a View-Model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.