Check if a string exists in an array case insensitively

前端 未结 11 1432
情歌与酒
情歌与酒 2020-12-09 07:45

Declaration:

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

then this

contains(listArray, word) 

Ret

相关标签:
11条回答
  • 2020-12-09 08:11

    Swift 4

    Just make everything (queries and results) case insensitive.

    for item in listArray {
        if item.lowercased().contains(word.lowercased()) {
            searchResults.append(item)
        }
    }
    
    0 讨论(0)
  • 2020-12-09 08:14

    swift 5, swift 4.2 , use the code in the below.

    let list = ["kAshif"]
    let word = "Kashif"
    
    if list.contains(where: { $0.caseInsensitiveCompare(word) == .orderedSame }) {
        print("contains is true")
    }
    
    0 讨论(0)
  • 2020-12-09 08:14

    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()
    }
    
    0 讨论(0)
  • 2020-12-09 08:15

    Try this:

    let loword = word.lowercaseString
    let found = contains(listArray) { $0.lowercaseString == loword }
    
    0 讨论(0)
  • 2020-12-09 08:18

    you can use

    word.lowercaseString 
    

    to convert the string to all lowercase characters

    0 讨论(0)
提交回复
热议问题