4

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.

1 Answer 1

4

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

Comments

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.