Check if array contains part of a string in Swift?

前端 未结 9 1072
无人共我
无人共我 2020-12-08 15:04

I have an array containing a number of strings. I have used contains() (see below) to check if a certain string exists in the array however I would like to chec

9条回答
  •  独厮守ぢ
    2020-12-08 15:26

    I had the same problem recently, didn't like most of these answers, solved it like this:

    let keywords = ["doctor", "hospital"] //your array
    
    func keywordsContain(text: String) -> Bool { // text: your search text
        return keywords.contains { (key) -> Bool in
            key.lowercased().contains(text.lowercased())
        }
    }
    

    This will also correctly trigger searches like "doc", which many of the above answers do not and is best practice. contains() is more performant than first() != nil source: https://www.avanderlee.com/swift/performance-collections/

提交回复
热议问题