gpt4 book ai didi

swift - 无法使用类型为 'AnyObject' 的索引下标类型为 'String' 的值

转载 作者:行者123 更新时间:2023-11-28 08:18:54 24 4
gpt4 key购买 nike

我试图获取标签的(名称)值

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

无法使用“String”类型的索引为“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."

}

}

最佳答案

将 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 中是没有意义的,如果值只是被读取的话,无论如何也是没有意义的。

关于swift - 无法使用类型为 'AnyObject' 的索引下标类型为 'String' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41792306/

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