搜索数组中的字符串

时间:2018-07-19 06:42:44

标签: ios swift

我有此代码:

[
  {
    "id": 176,
    "aSegments": [
      "CUT_SPECIALITIES1", 
      "CUT_SPECIALITIES2", 
      "CUT_SPECIALITIE2S"
    ],
    "sunFl": true,
    "inPi": false,
    "noBox": 72,
    "prepOven": "15 min / 220C"
  }
]

let searchString = "CUT_SPECIALITIES2"
let products = DataMgr.instance.getProducts(reload: false)
var productsObjectArray = products.filter({
   return  (($0.aSegments?.filter({
       $0.description.lowercased().contains(searchString.lowercased())
   }))?.count)! > 0
})

如何搜索CUT_SPECIALITIES2来查找搜索到的字符串?

1 个答案:

答案 0 :(得分:2)

这是我认为您拥有的数组:

let array = [
[
    "id" : 176,
    "aSegments": [
    "CUT_SPECIALITIES1",
    "CUT_SPECIALITIES2",
    "CUT_SPECIALITIE2S"
    ],
    "sunFl": true,
    "inPi": false,
    "noBox": 72,
    "prepOven": "15 min / 220C"
    ],
[
    "id" : 177,
    "aSegments": [
        "CUT_SPECIALITIES1",
        "CUT_SPECIALITIES2",
        "CUT_SPECIALITIE2S"
    ],
    "sunFl": true,
    "inPi": false,
    "noBox": 73,
    "prepOven": "18 min / 120C"
    ]
]

然后从此Array of Dictionaries开始,您要根据searchString过滤字典。

let searchString = "CUT_SPECIALITIES2"
let filteredArray = array.filter { (singleProduct) -> Bool in
    guard let aSegments = singleProduct["aSegments"] as? [String] else {
       return false
    }
    return (aSegments.filter({ $0 == searchString }).count > 0)
}

这将提供一个Array of Dictionaries,其中包含您搜索的字符串。