我正在关注的 Youtube 教程是:https://www.youtube.com/watch?v=ArfT4qOerL8
在 ContentView 部分代码的第 23 行和 64 行上,出现错误:
23:“WeatherData”类型的值没有成员“locationName”
64:“天气”类型的值没有成员“描述”
尽管完全按照我所看到的视频中的代码进行操作,但我收到了这些错误,而在视频中则没有。
这是我来自 Xcode 的代码副本:
//
// ContentView.swift
// TheWeatherAppSimple
//
// Created by Student02 on 09/05/2024.
//
import SwiftUI
import CoreLocation
struct ContentView: View {
@StateObject private var locationManager = LocationManager()
@State private var weatherData: WeatherData?
var body: some View {
VStack {
if let weatherData = weatherData {
Text("\(Int(weatherData.temperature))°C")
.font(.custom("", size: 70))
.padding()
VStack {
Text("\(weatherData.locationName)")
.font(.title2).bold()
Text("\(weatherData.condition)")
.font(.body).bold()
.foregroundColour(.gray)
}
Spacer()
Text("CodeLab")
.bold()
.padding()
.foregroundColour(.gray)
} else {
ProgressView()
}
}
.frame(width: 300, height: 300)
.background(.ultraThinMaterial)
.cornerRadius(20)
.onAppear {
locationManager.requestLocation()
}
.onReceive(locationManager.$location) { location in
guard let location = location else { return }
fetchWeatherData(for: location)
}
}
private func fetchWeatherData(for location: CLLocation) {
let apiKey = "df9c279067e67e66a494be48d6423329"
let urlString =
"https://api.openweathermap.org/data/2.5/weather?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)&units=metric&appid=\(apiKey)"
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) { data, _, error in guard let data = data else { return }
do {
let decoder = JSONDecoder()
let weatherResponse = try decoder.decode(WeatherResponse.self, from: data)
DispatchQueue.main.async {
weatherData = WeatherData(LocationName: weatherResponse.name,
temperature: weatherResponse.main.temp,
condition: weatherResponse.weather.first?.description ?? "")
}
} catch {
print(error.localizedDescription)
}
}
}
}
#Preview {
ContentView()
}
到目前为止,我已经通过 ChatGPT 运行代码来检查是否存在任何拼写错误。它给我的任何其他代码都会带来更多错误。我对 Swift 有非常基本的了解,所以我不确定我自己还能做些什么来尝试和修复。
编译器会告诉您错误是什么:
Value of type 'WeatherData has no member 'locationName'
Value of type 'Weather' has no member 'description'
修改这两个结构/类的定义以包含您引用的字段。