我有一個正在創建的天氣應用程式。我使用 API (OpenWeatherApp) 來獲取我的資料。weatherArray我將資料加載到型別為 的陣列中struct WeatherJSON。
我可以使用ForEach回圈成功訪問資料,但是當我嘗試使用 直接訪問特定資料時array[index],出現以下錯誤:Thread 1: Fatal error: Index out of range
這是我正在使用的頂級結構:
// holds all data from the JSON request
struct WeatherJSON: Codable {
var coord: Coord // coordinate struct
var weather: [Weather] // array of Weather struct
var base: String // "internal parameter..?"
var main: Main // main struct (contains the juicy data)
var visibility: Int // visibility number
var wind: Wind // wind struct
var clouds: Clouds // clouds struct
var dt: Int // time of data calculation, unix, UTC
var sys: Sys // internal parameer
var timezone, id: Int // timezone
var name: String // city namme
var cod: Int // another internal parameter (..?)
}
我的內容視圖:
struct ContentView: View {
@State private var weatherArray: [WeatherJSON] = []
// @State private var weatherArray: [Weather] = []
var body: some View {
NavigationView {
VStack {
Text("\(weatherArray[0].name)") // <---- This doesn't work
List {
// Text("Current conditions: \(weatherArray[0].description)")
// ForEach(weatherArray, id: \.self) { result in
// Section(header:Text("Address")) {
// Text("Current conditions: \(result.main)")
// .font(.headline)
// .bold()
// Text("Weather description: \(result.description)")
// .font(.body)
// }
// }
}
.navigationTitle("Weather")
}
}
.task { await handleData() }
}
func handleData() async {
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=Seattle&appid={APIKEY}") else {
print("This URL does not work!")
return
}
let decoder = JSONDecoder()
do {
let (weatherData, _) = try await URLSession.shared.data(from: url)
if let weatherObj = try? decoder.decode(WeatherJSON.self, from: weatherData) {
weatherArray.append(weatherObj)// = weatherObj.weather
print(weatherArray[0]) // <--- This works?
}
} catch {
print("Did not work :(")
}
} ```
uj5u.com熱心網友回復:
您的視圖正在weatherArray加載資料之前訪問。您需要考慮一個可能為空的陣列以避免崩潰。
改變:
Text("\(weatherArray[0].name)") // <---- This doesn't work
到:
Text("\(weatherArray.first?.name ?? "")")
uj5u.com熱心網友回復:
試試這個示例代碼,將天氣資料放入您的模型并在您的視圖中使用它:
public struct Weather: Identifiable, Codable {
public let id: Int
public let main, description, icon: String
}
struct Coord: Codable {
var lon: Double
var lat: Double
}
// holds all data from the JSON request
struct WeatherJSON: Codable {
var coord: Coord // coordinate struct
var weather: [Weather] // array of Weather struct
var base: String // "internal parameter..?"
var main: Main // main struct (contains the juicy data)
var visibility: Int // visibility number
var wind: Wind // wind struct
var clouds: Clouds // clouds struct
var dt: Int // time of data calculation, unix, UTC
var sys: Sys // internal parameer
var timezone, id: Int // timezone
var name: String // city namme
var cod: Int // another internal parameter (..?)
}
struct ContentView: View {
@State private var city: WeatherJSON?
var body: some View {
NavigationView {
VStack {
Text("\(city?.name ?? "no name")")
List {
ForEach(city?.weather ?? []) { weather in
Section(header:Text("Address")) {
Text("Current conditions: \(weather.main)")
.font(.headline)
.bold()
Text("Weather description: \(weather.description)")
.font(.body)
}
}
}
.navigationTitle("Weather")
}
}
.task { await handleData() }
}
func handleData() async {
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=Seattle&appid={apikey}") else {
print("This URL does not work!")
return
}
do {
let (weatherData, _) = try await URLSession.shared.data(from: url)
city = try JSONDecoder().decode(WeatherJSON.self, from: weatherData)
print(city)
} catch {
print("error: \(error)")
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478510.html
上一篇:檢查快速輸入?
