我会努力凝结。我正在解析包含数组中的数组的JSON。我无法弄清楚如何在嵌套数组中获取单个值
模型
struct WeatherForcastResponse: Codable {
let forcasts: [WeatherForcast]
private enum CodingKeys: String, CodingKey {
case forcasts = "list"
}
}
struct WeatherForcast: Codable {
let weatherDate: Double
let sunrise: Double
let sunset: Double
let weatherTemp: WeatherTemp
let weatherInfo: [WeatherTempInfo]
private enum CodingKeys: String, CodingKey {
case weatherDate = "dt"
case sunrise = "sunrise"
case sunset = "sunset"
case weatherTemp = "temp"
case weatherInfo = "weather"
}
}
// MARK: - DAILY 7 DAY
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 20) {
ForEach(weatherListForcastVM.forcasts, id: \.id) { forcast in
VStack {
ScrollView(.vertical, showsIndicators: false) {
VStack {
Text("\(DateExtensions.shared.convertDate(type: "Short", timezone: passedWeatherDetails.timeZone, passedDate: forcast.weatherDate))")
.bold()
//
//Text(weatherListForcastVM.weatherSkyInfo)
在我的视图模型中,我可以列出所有信息,但是如何在嵌套数组中生成特定值以与索引或父数组相对应?
class WeatherListForcastViewModel: ObservableObject {
@Published var forcasts = [WeatherForcastViewModel]()
@Published var weatherTempInfo = [WeatherTempInfo]()
var weatherSkyInfo = ""
private var weatherDescriptionInfo = ""
private var weatherIconInfo = ""
let jsonService = JSONService()
func getForcastByCityId(cityId: Int) {
jsonService.getCityWeatherById(cityId: cityId) { result in
switch result {
case .success(let details):
if let details = details {
DispatchQueue.main.async {
self.forcasts = details.map(WeatherForcastViewModel.init)
self.getWeatherItems()
}
}
case .failure(let error):
print(error.localizedDescription)
DispatchQueue.main.async {
print(error.localizedDescription)
}
}
}
}
func getWeatherItems() {
forcasts.forEach { (item) in
item.weatherTempInfo.forEach { (x) in
print("Forcast Description: \(x.sky)")
weatherSkyInfo = x.sky
}
}
}