Jamie McAllister Jamie McAllister - 11 months ago 42
iOS Question

can't resolve "Ambiguous use of subscript"

I wonder if someone can help me out here. I'm trying to convert a JSON response (from an

) into an array that i can use.

it's weird, This was working last night. however i now have a build error saying "ambiguous use of subscript"

let url = NSURL(string: "")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
//var boardings = [String]()

do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

if let theDogs = json[0] as? [[String: AnyObject]] {
for dog in theDogs {
if let ID = dog["ID"] as? String {
print(ID + " Safe")
let thisDog = Dog(name: (dog["Name"] as? String)!, surname: (dog["Surname"] as? String)!, id: (dog["ID"] as? String)!, boarding: true)
let newIndexPath = NSIndexPath(forRow: self.dogs.count, inSection: 0)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
} catch {
print("error serializing JSON: \(error)")

// print(names) // ["Bloxus test", "Manila Test"]



the error is on this line:
if let theDogs = json[0] as? [[String: AnyObject]] {

From what i could tell while looking other questions, the error is because of
, so i tried to change it to
[String: String]
but i still get the same error.

can anyone see the cause of this error?
any guidance you can offer would be greatly appreciated.


Extra Information

The JSON response being received from the server:


Answer Source

Looks like you are using the NSJSONSerialization, however you don't say what type of object you expect ( [AnyObject] or [String : AnyObject] ). They error you are getting is due to the fact you haven't casted to the json to [AnyObject].

PS: You might consider not using a force unwrap for the data (data!)

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [AnyObject]