2

I have searched long, but couldn't find a solution for my bug. Swift somehow doesn't count my array (converted from json) correctly. This is the code I use 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 count should be 3, the count is 2. So I just always added 1, but now if the count should be 4, the count is still 2.

Has anyone experienced something like that or is it just me doing something 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}]}
6
  • Can you provide an example of input that causes this problem? Commented Oct 12, 2014 at 20:42
  • You are referring to an array, but I see a dictionary - mistype, or the array is an element of the dictionary and you are counting the wrong object? Commented Oct 12, 2014 at 20:43
  • Yes it' a dictionary. No I'm counting the jsonDic (which is a dictionary) @Antonio Commented Oct 12, 2014 at 20:49
  • Confused... which one should have 3 elements? the dictionary or the array contained in it? Commented Oct 12, 2014 at 20:54
  • Ah I got it! Thanks! You were right, I was counting the dictionary, but I actually wanted to count the array in the dictionary. I am counting the array using: 'jsonDic["items"]!.count' @Antonio Commented Oct 12, 2014 at 20:57

1 Answer 1

3

The sample data you posted is a dictionary with one items key, and the corresponding value is an array (so the dictionary count should be 1).

By using this code:

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

I see that that array has 3 elements.

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

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

NOTE: I'd warn you about using jsonDic["items"]!.count because it is not safe: if the items key is not in the dictionary, or if its value cannot be cast to an array, then a run time exception will be thrown.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.