How do I parse an array inside parsed JSON in Swift?
ios, json, swift
Solution
Dictionary access in Swift returns an Optional, so you need to force the value (or use the `if let` syntax) to use it.
This works: `parsedJSON["boards"]![0]`
(It probably shouldn't crash Xcode, though)
Problem
I'm using an API that returns JSON that looks like this ``` { "boards":[ { "attribute":"value1" }, { "attribute":"value2" }, { "attribute":"value3", }, { "attribute":"value4", }, { "attribute":"value5", }, { "attribute":"value6", } ] } ``` In Swift I use two functions to get and then parse the JSON ``` func getJSON(urlToRequest: String) -> NSData{ return NSData(contentsOfURL: NSURL(string: urlToRequest)) } func parseJSON(inputData: NSData) -> NSDictionary{ var error: NSError? var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary return boardsDictionary } ``` and then I call it using ``` var parsedJSON = parseJSON(getJSON("link-to-API")) ``` The JSON is parsed fine. When I print out ``` println(parsedJSON["boards"]) ``` I get all the contents of the array. However I am unable to access each individual index. I'm positive it IS an Array, because ween I do ``` parsedJSON["boards"].count ``` the correct length is returned. However if I attempt to access the individual indices by using ``` parsedJSON["boards"][0] ``` XCode turns off syntax highlighting and gives me this: and the code won't compile. Is this a bug with XCode 6, or am I doing something wrong?