Check if a string exists in an array case insensitively

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

Declaration:

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

then this

contains(listArray, word) 

Ret

11条回答
  •  轮回少年
    2020-12-09 08:10

    SWIFT 3.0:

    Finding a case insensitive string in a string array is cool and all, but if you don't have an index it can not be cool for certain situations.

    Here is my solution:

    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"                                             
    }
    

    This is better than the other answers b/c you have index of the object in the array, so you can grab the object and do whatever you please :)

提交回复
热议问题