无法解决“下标的含糊使用" [英] Can't resolve "Ambiguous use of subscript"

查看:137
本文介绍了无法解决“下标的含糊使用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to convert a JSON response (from an NSUrlSession) 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: "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],但仍然遇到相同的错误.

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

任何人都可以看到此错误的原因吗?

Can anyone see the cause of this error?

从服务器收到的JSON响应:

The JSON response being received from the server:

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

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

推荐答案

看起来您正在使用NSJSONSerialization,但是您没有说期望使用哪种类型的对象([AnyObject]或[String:AnyObject]).他们得到的错误是由于您尚未将JSON强制转换为[AnyObject].

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:您可能会考虑不对数据(数据!)进行强制解包

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

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

这篇关于无法解决“下标的含糊使用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆