Swift For Loop Value of type "AnyObject"? doesn't have a member 'Generator'

I'm trying to do it, but he says

Value of type "AnyObject"? doesn't have a 'Generator' member

So this is my code.

let dataDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary var customerArray = dataDictionary.valueForKey("kart") for js: NSDictionary in customerArray { let nameArray: NSArray = js.valueForKey("name") } 

What am I doing wrong. I do not understand. Thanks for the help.

+6
source share
2 answers

Your customerArray is optional; is it of type AnyObject? (this is because .valueForKey returns optional). You cannot iterate over an option. The solution is to distinguish the result as an array in a safe deployment:

 if let customerArray = dataDictionary.valueForKey("kart") as? NSArray { for js in customerArray { let nameArray = js.valueForKey("name") // ... } } 
+8
source

This is because the valueForKey method returns an Optional value of AnyObject type ( AnyObject? ). Indeed, AnyObject does not have a Generator member and cannot be used in a for..in loop (as well as an Optional value). Thus, you must expand the optional value and apply it to the expected type, for example:

 let dataDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary var customerArray = dataDictionary.valueForKey("kart")! as! [NSDictionary] for js: NSDictionary in customerArray { let nameArray = js.valueForKey("name") as! NSArray } 
0
source

All Articles