【问题标题】:Remove Dictionary VALUE when value is of type Array当值是数组类型时删除字典值
【发布时间】:2023-02-09 23:20:00
【问题描述】:

我有一本字典是:

var myDictionary:[字符串:[字符串]]

它里面有一个项目列表,KEY 是项目字母的开头(类似于联系人列表),值是一个字符串数组。

myDictionary = [String: [String]] = [ "a": [
                "Ace", "Aemc", "Allegro", "Ames", "Amprobe", "Anvil", "Appion", "Apple", "Arrow"
            ],
            "b": [
                "Bacharach", "Bauer", "Big Tex", "Black & Decker", "BMW", "Bobcat", "Bosch", "Bostitch", "Brady", "Briggs & Stratton", "Brother", "Burndy"
            ]
    ] 
    

与搜索类似,我希望能够在 VALUES 数组中找到一个项目,但如果它确实存在,我想将其从字典中删除。意思是,在上面,我希望能够返回没有该项目的新字典。

因此,作为示例,根据上面的代码,如果我要输入 ACE,我想返回一个新的 Dictionary [String: [String]] WITHOUT 'Ace' in it.

现在我可以迭代通过以下方式找到的项目:

for items in myDictionary where items.value.contains("Ace")

但是我找不到一种方法来删除这个值条目。

我发现的所有搜索都只显示删除整个字典条目(通过键删除)而不是从值中删除实际项目。

非常感谢任何想法或建议。谢谢

【问题讨论】:

    标签: swift


    【解决方案1】:

    你必须移除原地的物品

    1. 将查询的第一个字母小写。
    2. 检查给定键的数组是否存在,如果可用则获取查询的索引
    3. 删除索引处的项目
      var myDictionary : [String: [String]] = [ "a": [
          "Ace", "Aemc", "Allegro", "Ames", "Amprobe", "Anvil", "Appion", "Apple", "Arrow"
      ],"b": [
          "Bacharach", "Bauer", "Big Tex", "Black & Decker", "BMW", "Bobcat", "Bosch", "Bostitch", "Brady", "Briggs & Stratton", "Brother", "Burndy"
      ]]
      
      let query = "Ace"
      let indexLetter = String(query.prefix(1).lowercased())
      if let value = myDictionary[indexLetter], let index = value.firstIndex(of: query) {
          myDictionary[indexLetter]!.remove(at: index)
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-12
      • 2019-04-30
      • 2022-12-10
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      相关资源
      最近更新 更多