Array counting speed

I searched for a long time but couldn't find a solution for my error. Swift somehow doesn't account for my array (converted from json) correctly. This is the code I am using to create the array:

let jsonData = NSData(contentsOfURL: url)
let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
var count = jsonDic.count

      

When the counter should be 3, the count is 2. So I always added 1, but now if the counter should be 4, the counter is still 2.

Has anyone experienced something like this, or is it just me something is wrong?

EDIT: This is an example input:

{"items":[{"var1":"xxx","var2":"xxx","var3":"xxx","var4":"xxx","var5":0},{"var1":"xxx","var2":"xxx","var3":"xxx","var4":"xxx","var5":0}, {"var1":"xxx","var2":"xxx","var3":"xxx","var4":"xxx","var5":0}]}

      

+3


source to share


1 answer


The summary you posted is a single key dictionary items

and the corresponding value is an array (so the number of words in the dictionary should be 1).

Using this code:

let array = jsonDic["items"] as? NSArray
array?.count

      

I can see that this array has 3 elements.



If what you are trying to count is an array, then I would use the above code, or this one using an optional binding:

if let array = jsonDic["items"] as? NSArray {
    array.count
}

      

NOTE . I would warn you to use jsonDic["items"]!.count

it because it is unsafe: if the key is items

not in the dictionary or its value cannot be passed to the array, then a runtime exception will be thrown.

+3


source







All Articles