Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - If inside ForEach loop

I am building a List based on my elements in an array I fetched before.

I am fetching all the entities.. when the user makes a search in the search bar, I want to filter my List. I am NOT doing a new FetchRequest, I just want to filter my objects.

That is the code I am using at the moment:

List(selection: $selectedDocument)
{
    ForEach(self.documentItems, id: \.self) { document in
        HStack(spacing: 0)
        {
            if (self.checkSearchString(document: document))
            {
                ListRow(document: document).tag(document)
            }
    }

I am having a List, then my ForEach loop. In that loop, I want to decide if I show that element or not. The problem is, that even if I do not want to show the element, there is still a small view inside my List. I know why, it is because I still render that HStack(). I basically need to drag that HStack() inside my If, however that is not working for me. I think it is because I need to render a view inside my List. But how can I contiuue my ForEach without rendering something.

That is what I want to achieve, BUT it is not working:

 List(selection: $selectedDocument)
 {
     ForEach(self.documentItems, id: \.self) { document in
         if (self.checkSearchString(document: document))
         {
             HStack(spacing: 0)
             {
                 ListRow(document: document).tag(document)
             }
         }

Thanks in advance!

like image 686
lvollmer Avatar asked Mar 26 '20 11:03

lvollmer


Video Answer


2 Answers

filter your data BEFORE passing it to ForEach constuctor.

ForEach(self.documentItems.filter {self.checkSearchString(document: $0)}, id: \.self) { document in
    HStack(spacing: 0)
        {
            ListRow(document: document).tag(document)
        }
}
like image 158
user3441734 Avatar answered Oct 19 '22 13:10

user3441734


You need to use Group to wrap different views provided by condition, like below

 ForEach(self.documentItems, id: \.self) { document in
   Group {
     if (self.checkSearchString(document: document))
     {
         HStack(spacing: 0)
         {
             ListRow(document: document).tag(document)
         }
     }
     else 
     {
        EmptyView()
     }
   }
 }
like image 29
Asperi Avatar answered Oct 19 '22 12:10

Asperi