如何在结构模型中访问枚举?迅速 [英] How to access enum within struct model? Swift

查看:36
本文介绍了如何在结构模型中访问枚举?迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在表中显示当前结构模型内的数据和时间.

I wanted to display in my tableView the data and time which is within the struct model right now.

我尝试访问view的主要WeatherModel结构,但是有一个[List]放弃了我访问dtTxt的权限.我只想在每一行中显示数据.任何帮助,将不胜感激.我在下面添加内容.

I tried accessing view the main, WeatherModel struct but there is a [List] which abandons me accessing the dtTxt. I just want to show the data in every row. Any help would be appreciated. I add my contents below.

控制器:

@IBOutlet var tableView: UITableView!

var weatherData = [WeatherModel]()

override func viewDidLoad() {
    super.viewDidLoad()

    getJSONData {
        self.tableView.reloadData()
    }

    tableView.delegate = self
    tableView.dataSource = self
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return weatherData.count

}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
    cell.textLabel?.text = weatherData[indexPath.row].city.name.capitalized // Instead of city name, it should be dtTxt.
    return cell
}

这是我的模特:

struct WeatherModel: Codable {
   let list: [List]
   let city: City
}

struct City: Codable {
   let name: String
}

struct List: Codable {
   let main: Main
   let weather: [Weather]
   let dtTxt: String // I want to show this

   enum CodingKeys: String, CodingKey {
      case main, weather
      case dtTxt = "dt_txt" //access here
   }
}

struct Main: Codable {
   let temp: Double
}

struct Weather: Codable {
   let main, description: String
 }

这是我的JSON对象:

And here is my JSON object:

      {
       "list": [
        {
        "main": {
            "temp": 277.12
        },
        "weather": [{
            "main": "Clouds",
            "description": "scattered clouds"
        }],
        "dt_txt": "2018-06-05 15:00:00"
    },
        {
        "main": {
            "temp": 277.12
        },
        "weather": [{
            "main": "Sunny",
            "description": "Clear"
        }],
        "dt_txt": "2018-06-05 18:00:00"
    },
        {
        "main": {
            "temp": 277.12
        },
        "weather": [{
            "main": "Rain",
            "description": "light rain"
        }],
        "dt_txt": "2018-06-05 21:00:00"
    }
],
"city": {
    "name": "Bishkek"
   }
}

推荐答案

[列表] 包含一组在不同时间的预测对象.

[List] contains an array of forecast objects at different times.

使用 for 循环:

for forecast in weatherModel.list {
    print(forecast.dtTxt)
}

或按特定条件过滤一个对象:

or filter one object by a certain condition:

if let threePMForecast = weatherModel.list.first(where: { $0.contains("15:00") }) {
    print(threePMForecast.dtTxt)
}

这篇关于如何在结构模型中访问枚举?迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆