Arrays 检查字典是否在Swift 3中的字典数组中

Arrays 检查字典是否在Swift 3中的字典数组中,arrays,swift,dictionary,contains,Arrays,Swift,Dictionary,Contains,我有一系列这样的字典: var suggestions = [["keyword": "apple", "identifier": "0"], ["keyword": "banana", "identifier": "1"], ["keyword": "carrot", "identifier": "2"]] 我想附加建议数组,在此之前,我想知道我的数组中是否已经存在字典以防止重复。我怎样才能在Swift 3中做到这一点 我试着为Swift 3使用contains(其中:([String:St

我有一系列这样的字典:

var suggestions = [["keyword": "apple", "identifier": "0"], ["keyword": "banana", "identifier": "1"], ["keyword": "carrot", "identifier": "2"]]
我想附加建议数组,在此之前,我想知道我的数组中是否已经存在字典以防止重复。我怎样才能在Swift 3中做到这一点

我试着为Swift 3使用
contains(其中:([String:String)])
函数,但我似乎无法让它工作

更新:丹尼尔·霍尔的回答让它起了作用。以下是Swift 3的准确代码:

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

应该简单到

suggestions.contains(where:{$0.contains(where:{$0=="keyword" && $1=="carrot"})})
检查“关键字”:“胡萝卜”键值对。语法有点麻烦,因为您正在查找某些内容中的某些内容

请注意,上面是完整查询的简写

suggestions.contains(where:{ 
(dict: [String:String])->Bool in  dict.contains(where:{
  (key: String, value: String) -> Bool in (key=="keyword" && value=="carrot") 
  })
})

这对您来说可能更简单,也可能不简单。

您可以创建一个表示数据类型的结构,而不是使用字典,如

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?
}
如果您想继续使用字典,可以使用
contains

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

我会选择struct选项。

我认为解决方案比其他答案更简单。只需使用:

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

这可以确保现有词典数组在添加之前不包含要添加的新词典。

另一个好的、简单的解决方案,Daniel Hall答案的可靠替代方案是:

let contains = suggestions.map(){$0 == newDictionary}.contains(true)
if !contains{
    suggestions.append(newDictionary)
}
我发布了这个答案,因为它没有使用
contains(其中:([String:String])抛出Bool)
函数



解释:基本上,
建议.map(){$0==newDictionary}
创建一个
[Bool]
在每个位置上包含一个
Bool
值,检查数组的该位置是否位于
newDictionary
。然后,
.contains(true)
检查新词典是否位于
建议
数组中的任何位置。

谢谢@Daniel Hall!我很惊讶,在这里使用
struct
这样简单。字典不应该仅仅用来存储一堆静态字段。更好的做法是将
条目
可散列
,并将
建议
设为
集合
。当你有时间时,你会将合并到问题中的答案转换为自我回答吗?这是这里回答材料的首选方法。谢谢