Foreach if all of a field is "0", return one view

Viewed 65

I'm trying to run through a list of items that all have a field called "yes" which is an integer. Essentially this loop runs through and if the yes field for an item is more than 0, it will show up, and if it is 0 it won't. Works as I want it to so far but what I would like to do is show a different message if ALL items have a 0 value, so that the section of the screen is not simply empty. How would I go about doing this? I tried putting the message into the "else" but (obviously) it just repeated the message the amount of times there are items in the db.

ForEach(items.indices, id: \.self) { i in
   if (items[i].yes != 0) {
      HStack {
         Text(items[i].name)
          Spacer()
          Text("\(items[i].yes)")
      }
      Divider()
   } else {}
}
1 Answers

You need something like below (typed in place, so might be typos):

if items.filter({ $0.yes != 0}).isEmpty {
   Text("Message for ALL are 0")
} else {
    ForEach(items.indices, id: \.self) { i in
       if (items[i].yes != 0) {
          HStack {
             Text(items[i].name)
              Spacer()
              Text("\(items[i].yes)")
          }
          Divider()
       } else {}
    }

}
Related