Reputation: 23
I have two arrays of dictionaries with type [String: String]. How can I check if one array contains dictionary from another.
let firstArray: [[String: String]] = [dict1, dict2, dict3]
let secondArray: [[String: String]] = [dict1, dict2, dict3, dict4, dict5]
I tried to do this with contains() method
for item in firstArray {
if secondArray.contains(item) {
print("Hello")
}
}
but it throw an error there. So what's the best way to do this?
Upvotes: 0
Views: 2547
Reputation: 3802
This works fine in Swift 4
let dictionary = ["abc":"pqr"]
if !myArray.contains{ $0 == dictionary } {
//append dictionary inside array
myArray.append(dictionary)
}
else {
//dictionary already exist in your myArray
}
Upvotes: 0
Reputation: 154583
You can use the predicate form of contains
to accomplish this:
for item in firstArray {
if secondArray.contains(where: { $0 == item }) {
print("Hello")
}
}
You can't use the other form of contains
because type [String : String]
does not conform to the Equatable protocol.
Upvotes: 2