如何判断WeatherKit的precipitationAmount单位?代码地区适配失效求助
WeatherKit precipitationAmount单位判断失效问题解决
你的代码问题出在WeatherKit返回的precipitationAmount原始单位始终是毫米(.millimeters),不会随系统地区设置自动切换。所以你直接判断原始单位的逻辑永远会命中第一个if,导致无论什么地区都显示"Millimeters"。
问题根源
WeatherKit提供的气象数据默认使用公制单位,precipitationAmount作为Measurement<UnitLength>类型,其原始单位固定为毫米,不会根据Locale自动转换。你需要手动处理单位转换或使用格式化工具适配地区。
修正方案
方案1:使用MeasurementFormatter自动适配地区
这是最推荐的方式,系统会根据当前Locale自动选择合适的单位并格式化:
let dWeather: Forecast<DayWeather> if let precipitation = dWeather.first?.precipitationAmount { let formatter = MeasurementFormatter() formatter.unitStyle = .long // 可选:.short(显示"mm"/"in")、.medium formatter.locale = Locale.current // 自动读取系统地区,也可手动指定如Locale(identifier: "en_US") Text(formatter.string(from: precipitation)) }
方案2:手动根据Locale转换单位
如果需要自定义显示逻辑,可以手动判断Locale并转换单位:
let dWeather: Forecast<DayWeather> if let precipitation = dWeather.first?.precipitationAmount { let targetUnit: UnitLength let currentLocale = Locale.current // 根据地区指定目标单位 if currentLocale.identifier == "en_US" { targetUnit = .inches } else { targetUnit = .millimeters } // 转换单位并格式化显示 let convertedPrecipitation = precipitation.converted(to: targetUnit) Text(String(format: "%.1f %@", convertedPrecipitation.value, targetUnit.symbol)) }
补充说明
如果你想验证原始单位,可以打印precipitationAmount.unit,会发现无论什么地区输出都是millimeters,这是WeatherKit的数据源特性决定的——所有地区的原始数据都用公制单位返回,单位转换需要客户端自行处理。
内容的提问来源于stack exchange,提问作者Alexnnd
相关产品推荐
相关产品推荐

