检查数组中是否存在字符串不敏感

Kas*_*hif 32 contains swift

宣言:

let listArray = ["kashif"]
let word = "kashif"
Run Code Online (Sandbox Code Playgroud)

那么这个

contains(listArray, word) 
Run Code Online (Sandbox Code Playgroud)

返回true但是如果声明是:

let word = "Kashif"
Run Code Online (Sandbox Code Playgroud)

然后它返回false,因为比较区分大小写.

如何使这个比较案例不敏感?

Leo*_*bus 39

let list = ["kashif"]
let word = "Kashif"

if contains(list, {$0.caseInsensitiveCompare(word) == NSComparisonResult.OrderedSame}) {
    println(true)  // true
}
Run Code Online (Sandbox Code Playgroud)

Xcode 7.3.1•Swift 2.2.1

if list.contains({$0.caseInsensitiveCompare(word) == .OrderedSame}) {
    print(true)  // true
}
Run Code Online (Sandbox Code Playgroud)

Xcode 8•Swift 3或更高版本

if list.contains(where: {$0.caseInsensitiveCompare(word) == .orderedSame}) {
    print(true)  // true
}
Run Code Online (Sandbox Code Playgroud)

或者:

if list.contains(where: {$0.compare(word, options: .caseInsensitive) == .orderedSame}) {
    print(true)  // true
}
Run Code Online (Sandbox Code Playgroud)


小智 23

您可以使用

word.lowercaseString 
Run Code Online (Sandbox Code Playgroud)

将字符串转换为所有小写字符


ios*_*ios 10

要检查数组中是否存在字符串(不区分大小写),请使用

listArray.localizedCaseInsensitiveContainsString(word) 
Run Code Online (Sandbox Code Playgroud)

其中listArray是数组的名称,word是您搜索的文本

此代码适用于Swift 2.2


Mar*_*one 8

试试这个:

let loword = word.lowercaseString
let found = contains(listArray) { $0.lowercaseString == loword }
Run Code Online (Sandbox Code Playgroud)


hga*_*ale 5

斯威夫特4

只要使所有内容(查询和结果)不区分大小写即可。

for item in listArray {
    if item.lowercased().contains(word.lowercased()) {
        searchResults.append(item)
    }
}
Run Code Online (Sandbox Code Playgroud)


Gov*_*wat 5

用于检查字符串是否存在于具有更多选项的数组中(不区分大小写,锚定/搜索仅限于启动)

使用基金会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
}
Run Code Online (Sandbox Code Playgroud)


Ala*_*din 5

您可以添加扩展名:

斯威夫特 5

extension Array where Element == String {
    func containsIgnoringCase(_ element: Element) -> Bool {
        contains { $0.caseInsensitiveCompare(element) == .orderedSame }
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

["tEst"].containsIgnoringCase("TeSt") // true
Run Code Online (Sandbox Code Playgroud)