如何解决使用WeatherKit获取逐小时气温时的类型不匹配错误?
解决WeatherKit中“Cannot assign value of type 'Forecast' to type '[HourWeather]'”错误
错误原因
调用WeatherService.shared.weather(for:including: .hourly)返回的是**Forecast类型**对象,但你定义的hourlyForecast是[HourWeather]数组类型,直接赋值导致类型不匹配。
修正方案
从返回的Forecast对象中提取逐小时天气数组——访问其hourly属性(该属性类型正好是[HourWeather]),替换原来的赋值语句。
修正后的代码
修改updateHourlyWeather函数:
func updateHourlyWeather(userLocation: CLLocation) { Task.detached(priority: .userInitiated) { do { let forecast = try await self.service.weather( for: userLocation, including: .hourly) DispatchQueue.main.async { self.hourlyForecast = forecast.hourly } } catch { print(error.localizedDescription) } } }
额外优化建议
- 修正变量名拼写:代码中
forcast应为forecast,提升可读性。 - 利用
@MainActor简化主线程切换:由于WeatherData类已被@MainActor修饰,可直接在Task中使用@MainActor,省去手动调用DispatchQueue.main.async:
func updateHourlyWeather(userLocation: CLLocation) { Task(priority: .userInitiated) { @MainActor in do { let forecast = try await self.service.weather( for: userLocation, including: .hourly) self.hourlyForecast = forecast.hourly } catch { print(error.localizedDescription) } } }
内容的提问来源于stack exchange,提问作者user04012001
相关产品推荐
相关产品推荐

