'Search multiple words in one string in swift

I have a long string in swift3 and want to check if it contains word1 and word2. It could also be more than 2 search words. I found out following solution:

var Text = "Hello Swift-world"
var TextArray = ["Hello", "world"]
var count = 0

for n in 0..<TextArray.count {
    if (Text.contains(TextArray[n])) {
        count += 1
    }
}

if (count == TextArray.count) {
    print ("success")
}

But this seems very complicated, is there not an easier way to solve this? (Xcode8 and swift3)



Solution 1:[1]

A more Swifty solution that will stop searching after it found a non-existent word:

var text = "Hello Swift-world"
var textArray = ["Hello", "world"]

let match = textArray.reduce(true) { !$0 ? false : (text.range(of: $1) != nil ) }

Another way to do it which stops after it found a non-match:

let match = textArray.first(where: { !text.contains($0) }) == nil

Solution 2:[2]

Another possibility is regular expressions:

// *'s are wildcards
let regexp = "(?=.*Hello*)(?=.*world*)"

if let range = Text.range(of:regexp, options: .regularExpression) {
    print("this string contains Hello world")
} else {
    print("this string doesn't have the words we want")
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community