Как получить доступ к enum в структурной модели?стриж - PullRequest
0 голосов
/ 09 июня 2018

Я хотел отобразить в моем tableView данные и время, которые сейчас находятся в структуре struct.

Я попытался получить доступ к главному представлению, структуре WeatherModel, но есть [Список], который не дает мне доступ к dtTxt.Я просто хочу показать данные в каждой строке.Любая помощь будет оценена.Я добавляю свое содержимое ниже.

Контроллер:

@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:

      {
       "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"
   }
}

1 Ответ

0 голосов
/ 09 июня 2018

[List] содержит массив объектов прогноза в разное время.

Используйте цикл for:

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

или отфильтруйте один объект по определенному условию:

if let threePMForecast = weatherModel.list.first(where: { $0.contains("15:00") }) {
    print(threePMForecast.dtTxt)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...