Brutus98
Brutus98

Reputation: 33

Filter Array of structs in Swift 4.0

I want to filter an array of structs via a searchBar. I know how to filter an array of strings, but unfortunately I am not able to apply this on a array of structs. Here is what I have already done:

var BaseArray: [dataStruct] = []

var filteredArray: [dataStruct] = []

The BaseArray is a Array of Structs with multiple variables. My Goal is to filter in all variables. Any ideas?

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == ""{
        isSearching = false
        view.endEditing(true)
        tableView.reloadData()
    }
    else{
        isSearching = true

        filteredArray = BaseArray.filter { $0.name == searchText }

        tableView.reloadData()
    }
}

Upvotes: 3

Views: 4823

Answers (1)

Jake
Jake

Reputation: 545

You will want to combine the positive results to include in your filtered array using the OR / union operator: ||

So your filter function will look like this:

filteredArray = BaseArray.filter { 
    $0.name == searchText
        || $0.anotherProperty == searchText
        || $0.yetAnotherProperty == searchText
}

This way, if either name or anotherProperty or yetAnotherProperty equals the text you are searching for, the result will be listed.

Additionally, you may wish to filter based on your input text containing the next, not needing to exactly equal it as in your example. In this case, your filter function will become:

filteredArray = BaseArray.filter {
    $0.name.contains(searchText)
        || $0.anotherProperty.contains(searchText)
        || $0.yetAnotherProperty.contains(searchText)
}

Upvotes: 8

Related Questions