jaytrixz jaytrixz - 4 years ago 139
Swift Question

Check if Dictionary is inside Array of Dictionaries in Swift 3

I have an array of dictionaries like this:

var suggestions = [["keyword": "apple", "identifier": "0"], ["keyword": "banana", "identifier": "1"], ["keyword": "carrot", "identifier": "2"]]

I would like to append the suggestions array and before I do that, I want to know if the dictionary already exists inside of my array to prevent duplicates. How can I do that in Swift 3?

I'm trying to use the
contains(where: ([String: String)])
function for Swift 3 but I can't seem to make it work. Any help would be appreciated. Thanks.

UPDATE: The answer by Daniel Hall made it work. Here's the exact code for Swift 3:

if !suggestions.contains(where: {0 == newDictionary}) {

Answer Source

I think the solution is more straightforward than the other answers suggest. Just use:

let newDictionary = ["keyword":"celery", "identifier": "3"]
if !suggestions.contains{ $0 == newDictionary } {

This makes sure that your existing array of dictionaries does not contain the new dictionary you want to add before appending it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download