9

I'm trying to replicate a for in loop I did in Objective C but am getting an "'AnyObject' does not have a member named 'GeneratorType' error:

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

Here is my Swift

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

I've tried defining a holder variable for the dictionary. Can anyone see what I'm doing wrong here, please?

iphonic
  • 12,615
  • 7
  • 60
  • 107
krisacorn
  • 831
  • 2
  • 13
  • 23

2 Answers2

20

This isn't a loop through a dictionary. It's looping though an array stored in one of the dictionaries keys. This is what would want to do if for example you had an array of strings as one of your dictionary's keys.

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

    }
}

If you do want to just loop through the dictionary though, this is possible in Swift, and can be done like this:

for (key, value) in dict {
    println("key is - \(key) and value is - \(value)")
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
2

One Liner for loop

dict.forEach { print("key is - \($0) and value is - \($1)") }
Masih
  • 1,633
  • 4
  • 19
  • 38