如何在Dictionary of Dictionary中搜索元素?

时间:2017-04-19 04:53:19

标签: ios arrays xcode search swift3

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

    (
        {
        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但由于条形码存在于数组中而无法正常工作。

3 个答案:

答案 0 :(得分:1)

您可以使用包含搜索词典数组,但在尝试比较之前需要将值从Any投射到Int

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

答案 1 :(得分:1)

**试试这个**

 // 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)")

答案 2 :(得分:0)

您还可以运行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"])")
   }
}

希望它有所帮助!