Reputation: 519
I want to count number of "items" in my json result for me to loop on it. Please see the code below which doesn't work for me:
var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary
for var i = 0; i < jsonResult["items"].count; i++ {}
It gives me following compile error: "AnyObject? doesnt have a member named count"
Can you please help me understand the reason behind it? and also, Can you please let me know the work around it?
Thanks for your help
Upvotes: 0
Views: 457
Reputation: 24714
Because jsonResult["items"]
this returnAnyObject?
,you have to convert it to real class it is.For example
var dic:NSMutableDictionary = NSMutableDictionary()
dic.setValue(["first","second","third"], forKey: "items")
var json:NSData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: nil)!
var jsondic = NSJSONSerialization.JSONObjectWithData(json, options:NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var jsonItems = jsondic["items"] as NSArray
for var i = 0;i < jsonItems.count; i++ {
println(jsonItems[i] as String)
}
This is the key
var jsonItems = jsondic["items"] as NSArray
You may use "as?",so that if convert fail,you app will not crash
var jsonItems = jsondic["items"] as? NSArray
if(jsonItems != nil){
for var i = 0;i < jsonItems!.count; i++ {
println(jsonItems![i] as String)
}
}
Upvotes: 1
Reputation: 1000
Because you're parsing dynamic data, the compiler can't make guarantees about what the JSON parser returns at runtime. For that reason, any value you retrieve from a JSON object is an optional you have to explicitly unwrap.
You can read about it at http://www.atimi.com/simple-json-parsing-swift-2/.
I believe there are libraries for JSON parsing in Swift now, that make this type of stuff a lot easier.
Upvotes: 2