【问题标题】:Loop through a dictionary in swift快速遍历字典
【发布时间】:2014-09-16 15:39:55
【问题描述】:

我正在尝试复制我在 Objective C 中执行的 for in 循环,但出现“'AnyObject' 没有名为 'GeneratorType' 的成员”错误:

 for (NSString *file in [dict objectForKey:@"Files"]){
    NSString *content = [[source stringByAppendingPathComponent:@"Contents"] stringByA
 }

这是我的斯威夫特

 for file in dict.objectForKey("Files") {
     let content:String = source.stringByAppendingPathComponent("Contents").stringByAppendingPathComponent(file)
 }

我尝试为字典定义一个持有者变量。谁能看到我在这里做错了什么?

【问题讨论】:

    标签: loops dictionary swift


    【解决方案1】:

    一个循环的内衬

    dict.forEach { print("key is - \($0) and value is - \($1)") }
    

    【讨论】:

      【解决方案2】:

      这不是通过字典循环。它正在循环存储在字典键之一中的数组。例如,如果您有一个字符串数组作为字典的键之一,这就是您想要做的。

      if let arr = dict["Files"] as? [String] {
          for file in arr {
      
          }
      }
      

      如果您确实只想遍历字典,这在 Swift 中是可能的,并且可以这样完成:

      for (key, value) in dict {
          println("key is - \(key) and value is - \(value)")
      }
      

      【讨论】:

      • 正是我尝试得到的,'Dictionary?'没有名为“生成器”的成员
      • 你需要先解开字典。
      猜你喜欢
      • 2015-05-19
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      相关资源
      最近更新 更多