如何从 SwiftyJSON 对象数组中搜索?

How to search from array of SwiftyJSON objects?

我有一个 SwiftyJSON 对象。

如何从 SwiftyJSON 对象的数组中按键(名称)搜索。

例如:

let arrCountry = [JSON]()

现在一个国家数组包含

{
    countryid : "1"
    name : "New York"
},
{
    countryid : "2"
    name : "Sydeny"
}

如何通过谓词或其他方式进行搜索?

如果我从数组中搜索 "y",那么它应该 return 两个对象(因为都包含 "y")在另一个 JSON 数组中。如果我键入 "Syd",那么它应该 return 在 JSON 数组中只有一个对象。作为 SQL 中的 LIKE 查询。正如我们对谓词所做的那样...

您需要从 JSON 对象中提取字典数组,然后您可以将谓词应用于该数组。

使用 arrayObjectJSON 对象获取数组,将其转换为正确的类型并应用 filter 函数,在本例中查找 [=15] 的项目=] 是 def

if let array = arrCountry.arrayObject as? [[String:String]],
   foundItem = array.first(where: { [=10=]["name"] == "def"}) {
   print(foundItem)
}

编辑:要使用 NSPredicateJSON 结果进行优化搜索,请使用此

let searchText = "y"
let searchPredicate = NSPredicate(format: "name contains[cd] %@", searchText)
if let array = arrCountry.arrayObject as? [[String:String]] {
    let foundItems = JSON(array.filter{ searchPredicate.evaluateWithObject([=11=]) })
    print(foundItems)
}