Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a dictionary in swift

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?

like image 314
krisacorn Avatar asked Jul 24 '14 21:07

krisacorn


People also ask

Can you loop through a dictionary in Swift?

Yes, you can. A Swift Dictionary supports iteration, just like an array.

How to iterate array of dictionary in Swift?

Let's use the for-in loop to iterate over the employee dictionary. It will print all the keys and values of the dictionary. However, we can also iterate over the reverse of the dictionary like an array. It will print the keys and values of the dictionary in reverse order.

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.


2 Answers

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)")
}
like image 86
Mick MacCallum Avatar answered Oct 06 '22 22:10

Mick MacCallum


One Liner for loop

dict.forEach { print("key is - \($0) and value is - \($1)") }
like image 40
Masih Avatar answered Oct 06 '22 22:10

Masih