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

根据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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:17:10