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

我有一个SwiftyJSON对象。

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

例如 :

let arrCountry = [JSON]() 

现在一个国家/地区arrays包

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

如何通过谓词或其他东西搜索?

如果我从数组中搜索“y”,那么它应该返回另一个JSON数组中的两个对象(因为两者都包含“y”)。 如果我输入“Syd”,那么它应该只返回JSON数组中的一个对象。 在SQL中作为LIKE查询。 正如我们在做谓词一样……

使用arrayObjectJSON对象获取数组,将其转换为正确的类型并应用filter函数,在此示例中查找namedef的项目

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

编辑:对于使用NSPredicateJSON结果的精确搜索, NSPredicate使用此选项

 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($0) }) print(foundItems) } 

您需要从JSON对象中提取字典数组,并且可以将Predicate应用于该数组。