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?
Yes, you can. A Swift Dictionary supports iteration, just like an array.
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.
There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.
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)")
}
One Liner for loop
dict.forEach { print("key is - \($0) and value is - \($1)") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With