例如,我正在处理一串配料(盐、水、面粉、糖),我想搜索这个字符串以查看特定项目是否在列表中(盐、面粉)
这是目前的代码
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/