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

SwiftUI中如何在ForEach里解包HourWeather的temperature.value?

如何在WeatherKit中安全处理HourWeather的temperature.value?

当然可行,不过首先需要明确:HourWeather的temperature属性是Measurement<UnitTemperature>类型,它的value是非可选的Double值,所以你当前代码中直接使用hour.temperature.value本身就是安全的,不需要额外解包。

如果希望和处理currentWeather的逻辑保持一致(给一个默认值兜底),可以通过以下两种方式实现:

方式一:在WeatherManager中统一处理

修改你的WeatherManager类,添加一个返回小时温度数组的计算属性,和unwrappedTemperature的处理逻辑对齐:

class WeatherManager: ObservableObject {
    // ... 原有代码保持不变

    var hourlyTemperatures: [Double] {
        // 遍历每小时天气,提取温度值,兜底默认值设为0
        unwrappedHourly.map { $0.temperature.value }
        // 如果你想严格对齐currentWeather的兜底逻辑,写法完全一致:
        // unwrappedHourly.map { $0.temperature.value ?? 0 }
        // 注:由于value本身非可选,这里的?? 0实际不会触发,但写法上和currentWeather统一
    }
}

然后在ContentView中直接使用这个属性:

ScrollView(.horizontal, showsIndicators: false) {
    HStack {
        ForEach(weatherManager.hourlyTemperatures.indices, id: \.self) { index in
            Text("\(weatherManager.hourlyTemperatures[index], specifier: "%.0f")°C")
        }
    }
}

方式二:在View中直接添加兜底逻辑

如果你不想修改WeatherManager,可以在遍历unwrappedHourly时直接给温度值加兜底,和你处理当前温度的逻辑保持一致:

ForEach(weatherManager.unwrappedHourly, id: \.date) { hour in
    Text("\(hour.temperature.value ?? 0, specifier: "%.0f")°C")
}

补充说明

为什么currentWeather需要解包?因为currentWeather是可选型(CurrentWeather?),所以需要用currentWeather?.temperature.value ?? 0来处理currentWeather为nil的情况。而unwrappedHourly已经通过hourWeather?.forecast ?? []处理成了非空数组,遍历出来的hour是确定存在的HourWeather实例,它的temperature和temperature.value都不会是nil,所以你原本的代码其实已经是安全的。

内容的提问来源于stack exchange,提问作者Alexnnd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:20:21