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

Swift中如何将Dictionary每个键对应的5个字符串值批量转换为Double类型

实现方案

方案1:解码时直接转换为数值类型(推荐)

直接在JSON解码阶段就将字符串格式的数值转为Double/Int类型,后续无需额外转换,代码最简洁:

struct TimeSeriesDaily: Codable {
    let open, high, low, close: Double
    let volume: Int64 // 交易量为整数,用Int64避免精度问题,也可按需改为Double
    
    enum CodingKeys: String, CodingKey {
        case open = "1. open"
        case high = "2. high"
        case low = "3. low"
        case close = "4. close"
        case volume = "5. volume"
    }
    
    // 自定义解码逻辑,先读字符串再转数值
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        open = try Double(container.decode(String.self, forKey: .open)) ?? 0
        high = try Double(container.decode(String.self, forKey: .high)) ?? 0
        low = try Double(container.decode(String.self, forKey: .low)) ?? 0
        close = try Double(container.decode(String.self, forKey: .close)) ?? 0
        volume = try Int64(container.decode(String.self, forKey: .volume)) ?? 0
    }
}

修改后你解码得到的tmpData.timeSeriesDaily直接就是[String: TimeSeriesDaily]结构,所有属性都是数值类型,可直接使用。

方案2:基于现有String模型转换为全数值字典

如果不需要修改原模型结构,可通过mapValues批量转换所有字段:

// 先定义存储数值的结构体
struct TimeSeriesDailyNumeric {
    let open: Double?
    let high: Double?
    let low: Double?
    let close: Double?
    let volume: Double?
}

// 转换代码,可直接放在ContentView的逻辑中
let numericDailyDict = filteredDict.mapValues { dailyData in
    TimeSeriesDailyNumeric(
        open: Double(dailyData.Open),
        high: Double(dailyData.High),
        low: Double(dailyData.Low),
        close: Double(dailyData.Close),
        volume: Double(dailyData.Volume)
    )
}

转换后的numericDailyDict结构和原JSON完全一致,所有值都是可选Double类型。

注意事项

  • 尽量避免使用强制解包!,可选值建议用if let/guard let绑定后再使用,避免空值崩溃
  • 交易量这类整数数值优先用Int64存储,比Double精度更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:18:01