Doe Doe - 4 months ago 19
Swift Question

How can I check if sentences in array contains exact words in Swift?

For example, I have the next arrays:

var reviews = ["Skating is good in Austria",
"I loved the Spanish food, it had so many varieties and
it was super super delicious. The price was a little bit high but
it was worth it. People who don't like spicy food might need
to think twice as it could be a little bit problematic for them.",
"I didn’t like the Indian food!",
"People were really friendly, I enjoyed being there."]

var words = ["Skating", "Food", "Climbing"]


Now I want to check, if these reviews contain one of my words.

The challenge is: One or more reviews can contain these words and I want to find these reviews, add them into an array and print.

For this I do:

var arr = [String]()

for review in reviews {
for word in words {
if review.containsString(word) {
arr.append(review)
}
}
print(arr)
}


but that prints only the first sentence:

["Skating is good in Austria"]


So, I want to check, if one or more reviews, contains on of these words from the array, then to put ALL these matched reviews into an
arr
array.

Can anyone help me with it? I'm confused why it take just one review and stop after

Answer

You need to move the print sentence out of your loop.

Like this:

var arr = [String]()

for review in reviews {
    for word in words {
        if review.containsString(word) {
            arr.append(review)
        }
    }
}
print(arr)

Also, if you don't want to get duplicate reviews, I would use a set instead of an array: var arr = Set<String>()

Also, it's probably the case that you need a case insensitive string comparison. Change Food by food in your words array and try again.

To get a full case insensitive loop working, try this:

for review in reviews {
    for word in words {
        if review.lowercaseString.containsString(word.lowercaseString) {
            arr.append(review)
        }
    }
}
print(arr)