Rajat Attri
Rajat Attri

Reputation: 23

How to search an element in Array of Dictionary?

Below mentioned is my array. I need to check if the barcode 8901058847857 or barcode xxxxxxxxxxx exists in array or not.

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

I tried using array.contains or array.elements but it is not working because barcode exists in an array.

Upvotes: 0

Views: 1205

Answers (3)

S.Singh
S.Singh

Reputation: 21

You can also run for loop to check the presence of element in your Array of dictionary.

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"])")
   }
}

Hope it helps!

Upvotes: 0

KKRocks
KKRocks

Reputation: 8322

** Try this **

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

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236340

You can search your array of dictionaries using contains where but you need to cast your value from Any to Int before trying to compare them:

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

Upvotes: 0

Related Questions