Check if a string exists in an array case insensitively

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

Declaration:

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

then this

contains(listArray, word) 

Ret

11条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 07:54

    Expanding on @Govind Kumawat's answer

    The simple comparison for a searchString in a word is:

    word.range(of: searchString, options: .caseInsensitive) != nil
    

    As functions:

    func containsCaseInsensitive(searchString: String, in string: String) -> Bool {
        return string.range(of: searchString, options: .caseInsensitive) != nil
    }
    
    func containsCaseInsensitive(searchString: String, in array: [String]) -> Bool {
        return array.contains {$0.range(of: searchString, options: .caseInsensitive) != nil}
    }
    
    func caseInsensitiveMatches(searchString: String, in array: [String]) -> [String] {
        return array.compactMap { string in
            return string.range(of: searchString, options: .caseInsensitive) != nil
                ? string
                : nil
        }
    }
    

提交回复
热议问题