【问题标题】:Search string for multiple substrings in iOS Swift在 iOS Swift 中搜索多个子字符串
【发布时间】:2015-10-06 19:57:13
【问题描述】:

例如,我正在处理一串成分(盐、水、面粉、糖),并想搜索此字符串以查看列表中是否包含特定项目(盐、面粉)

这是目前的代码

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

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

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

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

【问题讨论】:

    标签: ios string swift swift2


    【解决方案1】:

    您应该使用 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"])
    

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多