问题
I am trying to do this but it's says
Value of type 'AnyObject?' has no member 'Generator'
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 I am doing wrong.I didn't figure out.Thank you for your helps.
回答1:
Your customerArray is an Optional, it has the type AnyObject? (this is because .valueForKey returns an Optional). You can't loop over an Optional. Solution is to cast the result as an array while safe unwrapping:
if let customerArray = dataDictionary.valueForKey("kart") as? NSArray {
for js in customerArray {
let nameArray = js.valueForKey("name")
// ...
}
}
回答2:
It happend because valueForKey method returns Optional value of AnyObject type (AnyObject?). Indeed, AnyObject has no Generator member, and can't be used in for..in loop (as well as an Optional value). So, you should unwrap optional value and cast it to expected type, like this:
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
}
来源:https://stackoverflow.com/questions/33567231/swift-for-loop-value-of-type-anyobject-has-no-member-generator