How would I detect if a string contains any member of an array of strings (words)?
Here is the array:
let str:String = "house near the beach"
let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]
The following is not compiling
let match:Bool = wordGroups.contains(where: str.contains)
You can try
let str = Set("house near the beach")
let match = wordGroups.filter { str.contains($0) }.count != 0
In additional to answer of @Sh_Khan, if you want match some word from group:
let str:String = "house near the beach"
let wordGroups:[String] = ["beach","waterfront","with a water view","near ocean","close to water"]
let worlds = wordGroups.flatMap { $0.components(separatedBy: " ")}
let match = worlds.filter { str.range(of:$0) != nil }.count != 0
I am using String extension:
extension String {
func contains(_ strings: [String]) -> Bool {
strings.contains { contains($0) }
}
}
Use case:
let str = "house near the beach"
let wordGroups = ["beach","waterfront", "with a water view", "near ocean", "close to water"]
let haveWord = str.contains(wordGroups)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With