【问题标题】:Check if Dictionary is inside Array of Dictionaries in Swift 3检查字典是否在 Swift 3 中的字典数组中
【发布时间】:2017-06-23 17:56:03
【问题描述】:

我有一个这样的字典数组:

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)
}

【问题讨论】:

  • 当你有时间时,你会把合并到问题中的答案变成一个自我答案吗?这是此处回答材料的首选方法。谢谢!

标签: arrays swift dictionary contains


【解决方案1】:

另一个好的和直接的解决方案,一个可靠的替代丹尼尔霍尔的答案是:

let contains = suggestions.map(){$0 == newDictionary}.contains(true)
if !contains{
    suggestions.append(newDictionary)
}

我发布了这个答案,因为它不使用contains(where: ([String: String]) throws Bool) 函数。


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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 感谢@Daniel Hall!我很惊讶它看起来这么简单
    【解决方案3】:

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

    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 选项。

    【讨论】:

    • 使用struct 是这里的方法。字典不应该仅仅用来存储一堆静态字段。更好的做法是让EntryHashablesuggestions 成为Set
    【解决方案4】:

    应该像

    一样简单
    suggestions.contains(where:{$0.contains(where:{$0=="keyword" && $1=="carrot"})})
    

    您正在检查 "keyword":"carrot" 键值对的位置。语法有点麻烦,因为你要在某物里面找东西。

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

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

    这对你来说可能看起来更简单,也可能不简单。

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      相关资源
      最近更新 更多