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

标签 arrays swift dictionary contains

我有一组这样的字典:

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

我想附加建议数组,在执行此操作之前,我想知道该字典是否已存在于我的数组中以防止重复。我如何在 Swift 3 中做到这一点?

我尝试使用 Swift 3 的 contains(where: ([String: String)]) 函数,但我似乎无法让它工作。

更新:Daniel Hall 的回答使其有效。这是 Swift 3 的确切代码:

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

最佳答案

我认为解决方案比其他答案建议的更直接。只需使用:

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

这可以确保您现有的字典数组不包含您要添加的新字典,然后再追加它。

关于arrays - 检查字典是否在 Swift 3 中的字典数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42073756/

相关文章:

c++ - 外部变量和数组声明问题 C++

java - 处理数组中的重叠数字

ios - 将具有透视变换的 UIView 转换为 UIImage

ios - 没有 Unicode 的自定义 iOS 表情符号键盘

python - 将对象转换为 Panda 数据框?

arrays - 如何使用 jq 将 JSON 文件分解为包裹在数组中的较小 json?

arrays - 如何在AS3中向数组添加元素?

swift - 如何为 MacOS Big Sur 创建菜单栏 SwiftUI 应用程序

python - 过滤 Python 生成器表达式中的值

python - Pandas 'DataFrame' 对象没有属性 'map'