gpt4 book ai didi

ios - 无法解析 "Ambiguous use of subscript"

转载 作者:行者123 更新时间:2023-11-28 06:34:37 30 4
gpt4 key购买 nike

我正在尝试将 JSON 响应(来自 NSUrlSession)转换为我可以使用的数组。

很奇怪,这是昨晚的工作。但是我现在有一个构建错误,提示“下标的使用不明确”。

    let url = NSURL(string: "http://192.168.0.8/classes/main.php?fn=dogBoardingGet")
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.dogs.append(thisDog)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}

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

}

task.resume()

错误在这一行:if let theDogs = json[0] as? [[String: AnyObject]] {.

从我在查看其他问题时可以看出,错误是因为AnyObject,所以我尝试将其更改为[String: String],但我仍然得到同样的错误。

谁能看出这个错误的原因?

额外信息

从服务器接收到的 JSON 响应:

[[{"ID":"47","Name":"Sparky","Surname":"McAllister"}]]

最佳答案

看起来您正在使用 NSJSONSerialization,但是您没有说出您期望的对象类型( [AnyObject] 或 [String : AnyObject] )。您收到的错误是由于您没有将 json 转换为 [AnyObject]。

PS:您可能会考虑不对数据(数据!)使用强制解包

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

关于ios - 无法解析 "Ambiguous use of subscript",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389845/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com