使用Swift将JSON答案放入变量中



我试图将从JSON API获得的答案放入变量中。但它不起作用。它说info从未被使用过。我可以打印解码。控制台中的Data.name。但我不能把它放在变量中。我做错了什么?

我需要在这个函数之外使用这个变量。我试图在这个函数之外使用带有占位符的var-info,所以它不能说它没有被使用。但它没有起作用。

我得到错误:

从未使用过变量"info"的初始化;考虑用"_"的赋值替换或删除它。

func parseJSON(weatherData: Data) {
let decoder = JSONDecoder()
do{
let decodedData =  try decoder.decode(WeatherData.self, from: weatherData)
print(decodedData.name)

var info = decodedData.name

} catch {
print(error)
}
}

您可以从该函数返回数据,也可以像一样在该函数之外使用数据

func parseJSON(weatherData: Data)-> WeatherData? {
let decoder = JSONDecoder()
do{
let decodedData =  try decoder.decode(WeatherData.self, from: weatherData)
print(decodedData.name)

return decodedData

} catch {
print(error)
return nil

}
}

然后像这个一样使用它

if let info = parseJSON(weatherData: yourData) {
print(info.name)
}

最新更新