Check if a string exists in an array case insensitively

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

Declaration:

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

then this

contains(listArray, word) 

Ret

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 08:08

    For checking if a string exists in a array with more Options(caseInsensitive, anchored/search is limited to start)

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

提交回复
热议问题