简体   繁体   中英

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()
    }
}

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM