根据Windy API文档,需定义何种结构体解析近地面风数据?
解析Windy API近地面风数据的Codable结构体实现
Windy API响应中,近地面风常用参数为wind-10m(代表10米高度风场数据),同时units字典会包含该参数的单位信息。结合响应的动态字段特性,提供两种实现方案:
方案1:固定近地面风参数的结构体
仅针对wind-10m参数解析,代码简洁直接:
struct WindyResponse: Codable { var ts: [Int] var wind10m: [Double] var units: [String: String] enum CodingKeys: String, CodingKey { case ts, units case wind10m = "wind-10m" } }
使用时直接通过wind10m获取10米高度风数据,units["wind-10m"]获取对应单位。
方案2:支持动态风参数的通用结构体
兼容多高度风参数(如wind-2m等),通过字典存储动态字段:
struct WindyResponse: Codable { var ts: [Int] var units: [String: String] var windParameters: [String: [Double]] init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) ts = try container.decode([Int].self, forKey: .ts) units = try container.decode([String: String].self, forKey: .units) windParameters = [:] for key in container.allKeys { guard key != .ts && key != .units else { continue } windParameters[key.stringValue] = try container.decode([Double].self, forKey: key) } } enum CodingKeys: String, CodingKey { case ts, units } }
使用时通过windParameters["wind-10m"]获取对应高度的风数据。
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

