【问题标题】:How to get a Struct's value inside a Dictionary如何在字典中获取结构的值
【发布时间】:2020-10-18 16:47:58
【问题描述】:

这里是新手程序员!

我想在字典中获取嵌套结构的值,但无法访问字典。

这是我的结构

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
}

我尝试将其作为结构语法使用,但无法实现:

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

谢谢!

【问题讨论】:

    标签: ios swift xcode struct


    【解决方案1】:

    对不起我的愚蠢问题,我问这个真的很糟糕..

    我可以通过这个到达我的目的地:

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

    【讨论】:

    • 这个硬编码索引真的是你想要的吗?数组中的第一个索引为 0 而不是 1,如果列表仅包含一项或为空,您当前的代码会崩溃
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多