Can't resolve “Ambiguous use of subscript”

末鹿安然 提交于 2020-01-05 04:02:32

问题


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()

The error is on this line: if let theDogs = json[0] as? [[String: AnyObject]] {.

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?

Extra Information

The JSON response being received from the server:

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


回答1:


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: You might consider not using a force unwrap for the data (data!)

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


来源:https://stackoverflow.com/questions/39389845/cant-resolve-ambiguous-use-of-subscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!