You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:53:17