在swift中循环通过字典

kri*_*orn 7 dictionary loops swift

我正在尝试复制一个for循环,我在Objective C中做了但是得到一个"'AnyObject'没有名为'GeneratorType'的成员错误:

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

这是我的斯威夫特

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

我试过为dict定义一个holder变量.谁能看到我做错了什么,拜托?

Mic*_*lum 14

这不是字典中的循环.它通过存储在其中一个字典键中的数组循环.如果你有一个字符串数组作为你的字典键之一,那么这就是你想要做的.

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

    }
}
Run Code Online (Sandbox Code Playgroud)

如果你确实想要遍历字典,可以在Swift中实现,可以这样做:

for (key, value) in dict {
    println("key is - \(key) and value is - \(value)")
}
Run Code Online (Sandbox Code Playgroud)

  • 正是我试过的,'Dictionary <String,String>?' 没有名为'Generator'的成员 (3认同)