【问题标题】:Clearing every element of Arrays nested inside a Dictionary清除嵌套在字典中的数组的每个元素
【发布时间】:2014-07-31 13:14:15
【问题描述】:

使用字典中的嵌套字符串数组(带有字符串索引),我正在尝试创建一个函数,该函数允许我在调用时循环遍历字典的每个索引并将其替换为空数组。但是,执行以下代码会返回以下错误 <swift-imported-modules>:1: missing submodule 'cocoa'<REPL>:16:29: error: could not find an overload for 'subscript' that accepts the supplied arguments category[index] = [] 我不知道为什么

如果我只打印index,我会得到预期的类别字符串,如果我手动将它们输入循环,它会起作用,这只发生在index 被替换时。展开也无济于事。

class myClass {

    var category: Dictionary<String, Array<String>> = [
        "cat1" : [],
        "cat2" : [],
        "cat3" : []
    ]

    func eraseContent() {
        for index in category {
            category[index] = []
        }
    }
}

我也尝试查看参考指南,但没有找到 Swift 支持的 deleteAll 命令

【问题讨论】:

    标签: arrays dictionary swift for-in-loop


    【解决方案1】:

    您应该像这样访问category.keys

    func eraseContent() {
            for index in category.keys {
                category[index] = []
            }
        }
    

    【讨论】:

      【解决方案2】:

      我认为这就是你想要的。

      class myClass {
      
      var category: Dictionary<String, Array<String>> = [
          "cat1" : [],
          "cat2" : [],
          "cat3" : []
      ]
      func eraseContent(){
          for index in category {
              category[index.0] = []
          }
      }
      

      }

      【讨论】:

      • 您添加的-&gt; () 与作者拥有的没有区别。隐含返回值 void
      • 哦,抱歉,我的复制粘贴中留下了(我喜欢在我的代码中明确表示)
      • 非常感谢这个工作!必须在你的答案和 Jack 的答案之间做出选择,选择他的答案是因为它允许在 for 循环中包含更复杂的参数,而无需添加尽可能多的 '.0'(希望我可以同时选择两者)
      • 你也可以for (index, _) in category { category[index] = [] } 或者如果你想使用这个值,for (index, val) in category {...
      猜你喜欢
      • 2015-03-24
      • 2018-10-12
      • 2013-11-22
      • 1970-01-01
      • 2019-06-04
      • 2021-08-24
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多