Ios 如何在字典数组中搜索元素?

Ios 如何在字典数组中搜索元素?,ios,arrays,xcode,search,swift3,Ios,Arrays,Xcode,Search,Swift3,下面提到的是我的数组。我需要检查阵列中是否存在条形码8901058847857或条形码XXXXXXXXXX ( { barcode = 8901058847857; image = ( ); name = "Maggi Hot Heads"; productTotal = "60.00"; quantity = 3; }, {

下面提到的是我的数组。我需要检查阵列中是否存在条形码8901058847857或条形码XXXXXXXXXX

    (
        {
        barcode = 8901058847857;
        image =         (
        );
        name = "Maggi Hot Heads";
        productTotal = "60.00";
        quantity = 3;
    },
        {
        barcode = 8901491101837;
        image =         (
        );
        name = "Lays Classic Salted";
        productTotal = "20.00";
        quantity = 1;
    }
)

我尝试使用array.contains或array.elements,但由于数组中存在条形码,因此无法工作。

您可以使用contains where搜索词典数组,但在尝试比较它们之前,您需要将值从
Any
转换为
Int

if array.contains(where: {$0["barcode"] as? Int ?? 0 == 8901058847857}) { 
    print(true)
}
**试试这个**

 // Put your key in predicate that is "barcode"

var namePredicate = NSPredicate(format: "barcode contains[c] %@",searchString);

let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) };

print("names = ,\(filteredArray)")

您还可以运行for循环来检查字典数组中是否存在元素

let DictnaryArray =     (
        {
        barcode = 8901058847857;
        image =         (
        );
        name = "Maggi Hot Heads";
        productTotal = "60.00";
        quantity = 3;
    },
        {
        barcode = 8901491101837;
        image =         (
        );
        name = "Lays Classic Salted";
        productTotal = "20.00";
        quantity = 1;
    }
)

for (index,element) in DictnaryArray{

let dict = DictnaryArray[index]

   if dict["barcode"] == 8901058847857 || dict["barcode"] == XXXXXXXXXXX{
     print("BarCode Exist")
     print("\(dict["barcode"])")
   }
}

希望有帮助

你需要使用NSpredicate进行搜索。你能分享一些相同的例子吗?@RajatAttri在你的例子中,如果让res=yourArray,它就像
一样。首先(其中:{$0[“barcode”]as?String==searchingCode}{print(res)}
注意-如果是
数字
字符串
@NiravD Type any没有下标成员错误nirav条形码是Int而不是StringWelcome@rajattriyes,则将其转换为数字类型。它工作得很好。作为回报,我得到了整本词典。我对这一点有异议。我需要检查带有此条形码的产品是否存在。如果存在,则我需要在tableViewCell中将其标记为选中以继续。我不知道如何在tableViewCell中选择一个单元格而不点击ituser将扫描该项,如果该项已经在数组中,那么该单元格将位于顶部并将自身标记为选中。您是否使用model类解析json?它会抛出错误,因为我使用的是NSMutableArray,所以它表示表达式类型NSMutableArray在没有更多上下文的情况下不明确请检查此