Check if a string exists in an array case insensit

2019-01-25 02:39发布

Declaration:

let listArray = ["kashif"]
let word = "kashif"

then this

contains(listArray, word) 

Returns true but if declaration is:

let word = "Kashif"

then it returns false because comparison is case sensitive.

How to make this comparison case insensitive?

8条回答
不美不萌又怎样
2楼-- · 2019-01-25 03:33

My example

func updateSearchResultsForSearchController(searchController: UISearchController) {
    guard let searchText = searchController.searchBar.text else { return }
    let countries = Countries.getAllCountries()
    filteredCountries = countries.filter() {
        return $0.name.containsString(searchText) || $0.name.lowercaseString.containsString(searchText)
    }
    self.tableView.reloadData()
}
查看更多
\"骚年 ilove
3楼-- · 2019-01-25 03:34

Swift 4

Just make everything (queries and results) case insensitive.

for item in listArray {
    if item.lowercased().contains(word.lowercased()) {
        searchResults.append(item)
    }
}
查看更多
登录 后发表回答