Check if a string exists in an array case insensitively

you can use

word.lowercaseString 

to convert the string to all lowercase characters


For checking if a string exists in a array (case insensitively), please use

listArray.localizedCaseInsensitiveContainsString(word) 

where listArray is the name of array and word is your searched text

This code works in Swift 2.2


Xcode 8 • Swift 3 or later

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

if list.contains(where: {$0.caseInsensitiveCompare(word) == .orderedSame}) {
    print(true)  // true
}

alternatively:

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

if you would like to know the position(s) of the element in the array (it might find more than one element that matches the predicate):

let indices = list.indices.filter { list[$0].caseInsensitiveCompare(word) == .orderedSame }
print(indices)  // [0]

You can also use localizedStandardContains method which is case and diacritic insensitive and would match a substring as well:

func localizedStandardContains<T>(_ string: T) -> Bool where T : StringProtocol

Discussion This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

let list = ["kashif"]
let word = "Káshif"

if list.contains(where: {$0.localizedStandardContains(word) }) {
    print(true)  // true
}

Tags:

Contains

Swift