简体   繁体   中英

how can i filter array in swift 5 for search text in searchbar?

I am going to search from tableview and for that i used array.filter(), but i can not get any suggestion related to function's parameter, i got "NSArray.Element self", how can add my required parameter to function. i am not able to get a any function like "prefix" or "replaceString" in parameter, so i how can solve this issue?

here is my code,

extension ViewController: UISearchBarDelegate
{
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String)
{
searchCoin = ArrData.filter ({ $0.prefix(searchText.count) == searchText})
tableView.reloadData()
}
}

To check if any string element in the array contains the search text. Be it prefix, suffix or in between the string

extension ViewController: UISearchBarDelegate
{
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String)
    {
       searchCoin = ArrData.filter({ $0.contains(find: searchText)})
       tableView.reloadData()
    }
}

OR

To check if the any string element in the array has prefix equal to search text

extension ViewController: UISearchBarDelegate
{
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String)
    {
       searchCoin = ArrData.filter({ $0.hasPrefix(searchText)})
       tableView.reloadData()
    }
}

Swati is correct. Swift 5 has slightly different syntax but it's basically this. searchCoin is a new array filter of the original data array that you are searching.

let searchCoin = dataArray.filter({ $0.contains(searchText!)})

I solved my problem using:

let searchCoin = dataArray.filter({$0.lowercased().contains(searchText.lowercased())})

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