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

Swift如何高效交换嵌套字典内外层键 转换汇率数据结构?

实现方案

这类嵌套字典的键交换操作最低时间复杂度为O(T),T为所有内层键值对的总数量,没有办法绕过全量遍历的开销。下面提供两种Swift原生的高性能实现,性能优于未做优化的手动for循环:

方案1:简洁通用版(推荐绝大多数场景使用)

使用Swift优化过的reduce(into:)方法,不会产生多余的临时容器,性能和手动for循环持平,代码更易读:

// originalRates 为你从接口拿到的 [Date: [Currency Code : Amount]] 结构字典
let convertedRates = originalRates.reduce(into: [String: [String: Double]]()) { result, dateEntry in
    let date = dateEntry.key
    let currencyRates = dateEntry.value
    currencyRates.forEach { currency, amount in
        result[currency, default: [:]][date] = amount
    }
}

方案2:大容量数据优化版

如果你的日期范围跨度大、覆盖货币种类多,可以提前给字典分配足够容量,避免插入过程中频繁的内存扩容开销,数据量越大性能优势越明显:

// 提前统计所有货币种类与日期数量
let allCurrencies = Set(originalRates.values.flatMap(\.keys))
let totalDateCount = originalRates.count

// 提前初始化容量避免后续扩容
var convertedRates = [String: [String: Double]](minimumCapacity: allCurrencies.count)
originalRates.forEach { date, currencyRates in
    currencyRates.forEach { currency, amount in
        convertedRates[currency, default: .init(minimumCapacity: totalDateCount)][date] = amount
    }
}

两种方案最终输出的都是你需要的[Currency Code: [Date : Amount]]结构,可直接用于图表绘制逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:01