0

I was wondering, is there a way to get the result of a filter when there are no results?

At the moment, as a work around I have a ZStack and overlaying the results on top of a "No results" message.

But I was wondering if there was a conditional from the filter?

if(array.count > 0) {
  ForEach(array.filter({...}) { item in
    // do things if found
    //           <-- check if no results here
  }
} else {
  Text("No results at all")
}

I know that goes against the idea of the filtering, but thought I'd check in case I've missed something in all my searches!

markb
  • 1,100
  • 1
  • 15
  • 40
  • 1
    you wouldn't even enter the scope if no element is to be found in the list filtered list. What you could do is `let filtered = array.filter({...})` and then `if(filtered.count) {...}` and loop over the variable instead. if you need distinction between no result and no filtered results you can add an `else if (array.count > 0) { /*no filtered results*/ }` followed by `else { /*no result at all*/ }` – Olympiloutre Sep 12 '21 at 11:54
  • Smart @Olympiloutre - thank you that made it very quick and easy :) – markb Sep 12 '21 at 12:00
  • Your codes needs no improvement, having if- else is better to understand the code for another person reads your code. – ios coder Sep 12 '21 at 12:33
  • @swiftPunk `guard else` is another option though, you could make it all seem sequential, it depends on what is to be done in each case. However, the guard statement tend to be mainly used with `guard let else` which doesn't achieve anything here. FFT though. @markb you're welcome! – Olympiloutre Sep 13 '21 at 17:58
  • @Olympiloutre: I know about `guard let else` or `guard else` but I do not know if you had experience of using it in SwiftUI, guard has issue with SwiftUI, and in some situation it well let you down, and it can gave you an unknown issue or error, the safest way is using `If let` not `guard let` – ios coder Sep 13 '21 at 22:05
  • @swiftPunk thanks for the insight, I didn't have a chance to try SwiftUI yet, mainly because of this kind of rampants drawbacks. I'll keep it in mind. – Olympiloutre Sep 14 '21 at 09:28

2 Answers2

0

You need to check if your filtered array in if is empty:

let filteredArray = array.filter({...})
if !filteredArray.isEmpty {
    ForEach(filteredArray) { item in
        // do things if found
    }
} else {
    Text("No results at all")
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
0

Well it's answered already. But I want to add just one more change. Rather than using if better go with guard statement:

guard let filteredArray = array.filter({...}),
          !filteredArray.isEmpty else {
    Text("No results at all")
    return
}

ForEach(filteredArray) { item in
    // do things if found
}

You can read more about the difference here:

Amit
  • 4,837
  • 5
  • 31
  • 46