ios - 在 iOS Swift 中搜索多个子字符串的字符串

标签 ios string swift swift2

例如,我正在处理一串配料(盐、水、面粉、糖),我想搜索这个字符串以查看特定项目是否在列表中(盐、面粉)

这是目前的代码

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

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

在不重复 if 语句的情况下实现对多个子字符串的搜索的最佳方法是什么?

实际项目会搜索十几个子字符串,12个if语句是一个很尴尬的解决方案。

最佳答案

您应该使用 for 循环。

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

更好的是,将这个 for 循环添加为 String 类的扩展。

extension String {

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

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

        return occurrences
    }

}

然后你可以得到这样的事件:

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

关于ios - 在 iOS Swift 中搜索多个子字符串的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32978582/

相关文章:

ios - 当键盘出现时向上移动 UITextField

iphone - 是否不需要为IOS 4.0多任务支持方案保存状态?

ios - 点击时更改和保持 UICollectionView 单元格大小

arrays - 从字符串中逐字抓取字符

C++ 未使用我自己的字符串复制函数按预期打印

ios - 要求字典包含某些值(Swift)

ios - Carthage,在自己的框架中嵌入第三方框架

ios - 如何在 Swift 中控制其他 App 的背景音乐?

Swift DispatchQoS.QoSClass 转换为 DispatchQueue.Attributes

javascript - 如何替换javascript中的空格?