我在手机上部署应用时遇到“模糊使用下标”错误。
我有以下格式的JSON响应:
[
{
"title":"G1",
…
},
{
"title":"G2”,
…
}
]
这是我的代码:
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()
我的错误发生在以下一行:
if let item = jsonResult[index] as? [String: AnyObject] {
当我第一次与json合作时,请有人帮助我。我不确定我的代码结构是否支持上面的json模式。任何帮助将不胜感激。
答案 0 :(得分:0)
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
您应该将jsonResult
转换为AnyObject数组
guard let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] else {
return
}