Applying multiple filters to struct in List

I am trying to apply multiple filters to a struct in a List.

The following code is the main search control filter:

@State private var includeInactive : Bool = false
@State private var searchText: String = ""
@State private var isEditing = false

List(clientData.Clients.filter({
                searchText.isEmpty ? true : $0.fullname.lowercased().contains(searchText.lowercased())
                 }) ) { ClientLimited in

The code for the search filter works fine.

The question is, how do I add query elements. I want to also filter this list on an element called inactive from the includeInactive Bool, which is set by a toggle.

I can change the filter as follows:

@State private var includeInactive : Bool = false

List(clientData.Clients.filter({
                includeInactive == true ? true : $0.inactive == false
                 }) ) { ClientLimited in

This filters the data correctly for the inactive control.

How do you add both of these into one filter?

Replies

I probably miss something.

Did you try simply this ?

List(clientData.Clients.filter({
            (searchText.isEmpty || includeInactive) ? true : ($0.fullname.lowercased().contains(searchText.lowercased()) && !$0.inactive)
                 }) ) { ClientLimited in

Logic is the following.

Your conditions are:

  • a ? true : test1

and

  • b ? true : test 2

To join the 2 :

  • if a or b is true: then true
(a || b) ? true

otherwise, that means both a and b are false. Hence the second part will be true if test1 and test2 are true

So the full condition is:

(a || b) ? true : (test1 && test2)

In your case:

  • a = searchText.isEmpty
  • b = includeInactive == true, which can be simply written includeInactive
  • test1 = $0.fullname.lowercased().contains(searchText.lowercased()
  • test2 = $0.inactive == false, which can simply be written  !$0.inactive