2017-04-19 81 views
1

下面提到的是我的數組。我需要檢查數組中是否存在條形碼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但它不工作,因爲條形碼陣列中的存在。

+0

您需要使用NSpredicate進行搜索。 – KKRocks

+0

你能分享任何相同的例子嗎? –

+0

@RajatAttri在你的情況下,它就像'if let res = yourArray.first(其中:{$ 0 [「barcode」] as?String == searchingCode}){ print(res) } **注意 - **如果數字類型爲'數字'而不是'字符串',則將'barcode'強制轉換爲數字類型 –

回答

0

**嘗試此方法**

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

這工作正常。謝謝@KKRocks –

+0

歡迎@RajatAttri – KKRocks

+0

這是接受的答案? – KKRocks

1

可以使用包含搜索你的字典數組,其中,但你需要嘗試對它們進行比較之前,你的價值投從AnyInt

if array.contains(where: {$0["barcode"] as? Int ?? 0 == 8901058847857}) { 
    print(true) 
} 
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"])") 
    } 
} 

希望它有幫助!

+0

它是拋出錯誤,因爲我正在使用NSMutableArray所以它是說表達式類型NSMutableArray是不明確的沒有更多的上下文 –

+0

檢查此http://stackoverflow.com/questions/35680790/expression-type-nsmutablearray-is-ambiguous-without-more -context –