Swift For Loop Value of type 'AnyObject?' has no member 'Generator'

穿精又带淫゛_ 提交于 2020-01-01 10:12:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!