CM.
CM.

Reputation: 519

Search string for multiple substrings in iOS Swift

I am working with a string of ingredients (salt, water, flour, sugar) for example, and want to search this string to see if specific items are on the list (salt, flour)

This is the code so far

let ingredientList = (JSONDictionary as NSDictionary)["nf_ingredient_statement"] as! String

if ingredientList.lowercaseString.rangeOfString("salt") != nil {
    print("Salt Found!")
}

What would be the best way to implement a search for multiple substrings without repeating if statements?

The actual project will search for a dozen substrings, and 12 if statements is a pretty awkward solution.

Upvotes: 4

Views: 1467

Answers (1)

tanner0101
tanner0101

Reputation: 4065

You should use a for-loop.

for ingredient in ["salt", "pepper"] {
    if ingredientList.rangeOfString(ingredient) != nil {
        print("\(ingredient) found")
    }
}

Even better, add this for-loop as an extension to the String class.

extension String {

    func findOccurrencesOf(items: [String]) -> [String] {
        var occurrences: [String] = []

        for item in items {
            if self.rangeOfString(item) != nil {
                occurrences.append(item)
            }
        }

        return occurrences
    }

}

Then you can get the occurrences like this:

var items = igredientList.findOccurrencesOf(["salt", "pepper"])

Upvotes: 4

Related Questions