Ответ 1
вы можете использовать
word.lowercaseString
чтобы преобразовать строку ко всем строчным символам
Декларация:
let listArray = ["kashif"]
let word = "kashif"
то это
contains(listArray, word)
Возвращает true, но если декларация:
let word = "Kashif"
то он возвращает false, потому что сравнение чувствительно к регистру.
Как сделать этот случай сравнения нечувствительным?
вы можете использовать
word.lowercaseString
чтобы преобразовать строку ко всем строчным символам
let list = ["kashif"]
let word = "Kashif"
if contains(list, {$0.caseInsensitiveCompare(word) == NSComparisonResult.OrderedSame}) {
println(true) // true
}
Xcode 7.3.1 • Swift 2.2.1
if list.contains({$0.caseInsensitiveCompare(word) == .OrderedSame}) {
print(true) // true
}
Xcode 8 • Swift 3 или более поздняя версия
if list.contains(where: {$0.caseInsensitiveCompare(word) == .orderedSame}) {
print(true) // true
}
альтернативно:
if list.contains(where: {$0.compare(word, options: .caseInsensitive) == .orderedSame}) {
print(true) // true
}
если вы хотите узнать положение (я) элемента в массиве (может быть найдено более одного элемента, соответствующего предикату):
let indices = list.indices.filter { list[$0].caseInsensitiveCompare(word) == .orderedSame }
print(indices) // [0]
Чтобы проверить, существует ли строка в массиве (регистр нечувствителен), используйте
listArray.localizedCaseInsensitiveContainsString(word)
где listArray - это имя массива и слово - ваш искомый текст.
Этот код работает в Swift 2.2
Попробуйте следующее:
let loword = word.lowercaseString
let found = contains(listArray) { $0.lowercaseString == loword }
Swift 4
Просто сделайте все (запросы и результаты) нечувствительными к регистру.
for item in listArray {
if item.lowercased().contains(word.lowercased()) {
searchResults.append(item)
}
}
SWIFT 3.0:
Поиск строки, нечувствительной к регистру в строковом массиве, классный и все, но если у вас нет индекса, он не может быть крутым в определенных ситуациях.
Вот мое решение:
let stringArray = ["FOO", "bar"]()
if let index = stringArray.index(where: {$0.caseInsensitiveCompare("foo") == .orderedSame}) {
print("STRING \(stringArray[index]) FOUND AT INDEX \(index)")
//prints "STRING FOO FOUND AT INDEX 0"
}
Это лучше, чем другие ответы b/c, у вас есть индекс объекта в массиве, поэтому вы можете захватить объект и делать все, что угодно:)
Для проверки, существует ли строка в массиве с большим количеством опций (caseInsensitive, привязка/поиск ограничен началом)
range(of:options:)
Foundation range(of:options:)
let list = ["kashif"]
let word = "Kashif"
if list.contains(where: {$0.range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
print(true) // true
}
if let index = list.index(where: {$0.range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
print("Found at index \(index)") // true
}
Мой пример
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()
}