15

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)
3
  • 4
    Your code compiles for me (and returns true). What error are you getting? Commented Oct 8, 2018 at 23:13
  • 'Call can throw but it is not marked with 'try' and the error is not handled' plus an unwrapping error.The compiler eventually accepted let match:Bool = self.wordGroups.contains(where: (str?.contains)!) Commented Oct 10, 2018 at 5:33
  • There's nothing in the question that should throw or need to be unwrapped, so I assume your real code is a little different and the problem is somewhere else. Be careful unless you're absolutely 100% certain str will never be nil. Commented Oct 10, 2018 at 17:07

3 Answers 3

16

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)
Sign up to request clarification or add additional context in comments.

Comments

12

You can try

let str = Set("house near the beach")
let match = wordGroups.filter { str.contains($0) }.count != 0

Comments

8

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

1 Comment

It is not effective to use filter because you need just first element which matches condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.