gpt4 book ai didi

ios - 不能对类型为 'Any' SWIFT 的非可选值使用可选链接

转载 作者:搜寻专家 更新时间:2023-10-31 22:58:34 24 4
gpt4 key购买 nike

我对 Swift 非常陌生,我在构建一个天气应用程序时遇到了问题,该应用程序利用了来自名为 openweathermap.org 的网站的 API。当用户输入一个城市并单击“提交”时,他们应该能够看到一个显示天气描述的标签。

JSON 格式的结果是:

(
{
description = haze;
icon = 50d;
id = 721;
main = Haze;
},
{
description = mist;
icon = 50d;
id = 701;
main = Mist;
}
)

在尝试调试时,我使用了代码:print(jsonResult["weather"]!) 这让我可以看到上面的 JSON 详细信息。但是,当我尝试获取天气描述时,我似乎无法让它工作。

我的目标:我试图让天气描述显示在我的应用程序上。我目前收到错误:无法对“任何”类型的非可选值使用可选链接。非常感谢您的帮助!

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var cityTextField: UITextField!

@IBOutlet weak var resultLabel: UILabel!


@IBAction func submit(_ sender: AnyObject) {
// getting a url
if let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=" + (cityTextField.text?.replacingOccurrences(of: " ", with: "%20"))! + ",uk&appid=08b5523cb95dde0e2f68845a635f14db") {

// creating a task from the url to get the content of that url
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("error")
} else {
print("no error")
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any]
//print(jsonResult["weather"]!)
if let description = jsonResult["weather"]??[0]["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 a different city."
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}

最佳答案

试试这个

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any]


let weather = jsonResult["weather"] as! [[String : Any]]
if let description = weather[0]["description"] as? String {

print(description)
}

关于ios - 不能对类型为 'Any' SWIFT 的非可选值使用可选链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40767292/

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