user7205816 user7205816 - 15 days ago 5
Swift Question

"Ambiguous use of subscript" error while deploying - Swift 3

I am getting "Ambiguous use of subscript" error while deploying app on phone.

I have a JSON response in the following format:

[
{
"title":"G1",

},
{
"title":"G2”,

}
]


This is my code:

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in // URLSession.shared().dataTask(with: url) { (data, response, error) is now URLSession.shared.dataTask(with: url) { (data, response, error)

if error != nil {

print(error)

} else {

if let urlContent = data {

do {

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject


for index in 0...jsonResult.count-1 {

if let item = jsonResult[index] as? [String: AnyObject] {
if let loc = item["title"] as? String {
self.locArr.append(loc)
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}

} catch {

print("JSON Processing Failed")
}
}
}
}

task.resume()


My error is coming on the following line:

if let item = jsonResult[index] as? [String: AnyObject] {


Please someone help me as I am working with json for the first time. I am not sure if my code structure supports the above json pattern. Any help would be greatly appreciated.

Answer
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

you should cast your jsonResult as an array of AnyObject

guard let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] else {
  return
}