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

标签 ios json swift nsurlsession

我正在尝试将 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/

相关文章:

android - 从电子邮件中打开 Android ios 应用程序

iphone - iOS:google+ sdk 在授予 google+ 权限后重定向到 google.com,而不是重定向回应用程序

objective-c - 如何在 Objective-C 中遍历一个简单的 JSON 对象?

json - 如何将 png 文件包含在 JSON 文件的 Swift 对象中?

swift - 为什么我们不能转换为具有关联类型的协议(protocol)类型,而是使用泛型达到相同的效果?

ios - 在我的 IOS 应用程序中销售数字内容和实体书应该遵循哪种付款程序

ios - 在 iPad 中加载 PDF

javascript - 如何使用 Javascript 更改本地存储中项目的值

java - "Relaxed"Jackson 的字段名称

ios - 每次调试测试后文档位置发生变化