不能下标类型' AnyObject'的值。索引类型'字符串'

时间:2017-01-22 14:46:55

标签: swift

我试图将(名称)值添加到标签

我使用resultLabel.text = !(jsonResult["name"])但它返回错误

无法下标类型' AnyObject'索引类型为'字符串'

See my JSON

并且有人知道如何获取数据..

我的代码....

    if let url = URL(string: "http://www.omdbapi.com/?t=The+Raid&y=&plot=short&r=json") {

    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 // Added "as anyObject" to fix syntax error in Xcode 8 Beta 6

                    print(jsonResult)

                    print(jsonResult["Title"])

                    resultLabel.text = (jsonResult["name"])

                    if let description = ((jsonResult["weather"] as? NSArray)?[0] as? NSDictionary)?["description"] as? String {

                        DispatchQueue.main.sync(execute: {

                            self.resultLabel.text = description
                        }) 
                    }
                 } catch {

                    print("JSON Processing Failed")
                }
            }
         }
    }

    task.resume()

    } else {

        resultLabel.text = "Couldn't find weather for that city - please try another."

    }

}

1 个答案:

答案 0 :(得分:0)

将JSON反序列化的结果转换为AnyObject是您可以做的最糟糕的事情。

首先,未指定的JSON类型为Any,因为该类型应该是字典,所以将其强制转换为[String:Any]

此外,在Swift 3中,编译器必须知道所有下载的类型

        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as! [String:Any]
            let name = jsonResult["name"] as? String
            print(name ?? "n/a")
            if let weather = jsonResult["weather"] as? [[String:Any]], !weather.isEmpty { 
                if let description = weather[0]["description"] as? String {
                    DispatchQueue.main.async { // not sync !!
                        self.resultLabel.text = description
                    }
                }
...

PS:与往常一样,如果只读取值,mutableContainers在Swift中毫无意义,毫无意义。