Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 tried to use the contains(where: ([String: String)]) function for Swift 3 but I can't seem to make it work.

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

let newDictionary = ["keyword": "celery", "identifier": "3"]
if !suggestions.contains(where: {$0 == newDictionary}) {
    suggestions.append(newDictionary)
}
like image 932
jaytrixz Avatar asked Dec 18 '22 09:12

jaytrixz


2 Answers

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 } {
    suggestions.append(newDictionary)
}

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

like image 178
Daniel Hall Avatar answered Jan 13 '23 12:01

Daniel Hall


Instead of using dictionaries, you can create a struct representing your data types like.

internal struct Entry {
    let id: String
    let keyword: String
}

extension Entry: Equatable {
    static func == (lhs: Entry, rhs: Entry) -> Bool {
        return lhs.id == rhs.id && lhs.keyword == rhs.keyword
    }
}

let suggestions: [Entry] = [] //...
let newEntry = Entry(id: "3", keyword: "orange")


if suggestions.contains(newEntry) {
    // Do Something
} else {
    // Insert maybe?
}

If you prefer to just keep using dictionary, you can use contains

let newEntry = ["keyword": "orange", "identifier": "4"]
let containsEntry = suggestions.contains{ $0["identifier"] == newEntry["identifier"] }
if containsEntry {
    // Do something
} else {
    // Insert maybe?
}

I would go for the struct option .

like image 44
Camo Avatar answered Jan 13 '23 10:01

Camo