提问者:小点点

如何在字典中获取结构的值


新程序员来了!

我想在字典中获取嵌套结构的值,但是我无法在字典中找到它。

这是我的结构

struct Forecast: Decodable {
    let cod: String
    let message: Int
    let cnt: Int
    let list: [List]
    let city: City
}

struct List: Decodable {
    let dt: Int
    let main: Main
    let weather: [Weather]
    let clouds: Clouds
    let wind: Wind
    let sys: Sys
    let dt_txt: String
    
    private enum CodingKeys: String, CodingKey {
        case dt, main, weather, clouds, wind, sys, dt_txt = "dt_txt"
    }
}

struct Main: Decodable {
    let temp: Double                           // I want to get this!
    let feels_like: Double
    let temp_min: Double
    let temp_max: Double
    let pressure: Int
    let sea_level: Int
    let grnd_level: Int
    let humidity: Int
    let temp_kf: Double
}

我试图将其作为struct语法实现,但无法实现:

self.tempLbl.text = "\(Int(round(weather.list.main.temp)) - 273)°" 
// Value of type '[List]' has no member 'main'

谢谢!


共1个答案

匿名用户

抱歉,我问了个愚蠢的问题,我真的很抱歉。

我能够用这个到达我的目的地:

self.tempLbl.text = "\(Int(round(weather.list[1].main.temp)) - 273)°"
// weather.list[1].main.temp