Swift天气应用开发报错求助:WeatherData与Weather成员缺失
Swift天气应用开发报错求助
我正在跟随YouTube上的Swift天气应用制作教程,但遇到两个错误导致无法完成开发:
- 第23行报错:
Value of type 'WeatherData' has no member 'locationName' - 第64行报错:
Value of type 'Weather' has no member 'description'
我对照视频代码逐行编写,视频中并未出现此类报错。已用ChatGPT检查拼写,未发现拼写错误,但ChatGPT给出的修改方案反而引发更多错误。由于Swift基础薄弱,无法自行解决,特此求助。
以下是我在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 = "xxxxxxxxxxxxxxxx" 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() }
内容的提问来源于stack exchange,提问作者Owen
相关产品推荐
相关产品推荐

