【问题标题】:Swift map nested dictionary to swap outer and inner keysSwift映射嵌套字典以交换外部和内部键
【发布时间】:2021-12-26 02:36:18
【问题描述】:

我正在 swift 中构建一个应用程序,它显示多个图表,其中一个是汇率图表,可以通过 UITableView 中的货币代码和日期范围进行过滤。我能够成功地从https://fixer.io/ 中提取 FX 数据并将该 json 数据转换为以下 swift 结构:

struct FetchedFXRateByDate: Codable {
let success, timeseries: Bool
let startDate, endDate, base: String
let rates: [String: [String: Double]] // [Date: [Currency Code : Amount]]

enum CodingKeys: String, CodingKey {
    case success, timeseries
    case startDate = "start_date"
    case endDate = "end_date"
    case base, rates
}

}

我现在想要的是操作或“映射”/“过滤”内部 dict 'let rates: [String: [String: Double]]',以转换 dict:

发件人:

[String: [String: Double]] // [日期: [货币代码 : Amount]]

收件人:

[String: [String: Double]] // [货币代码: [Date : Amount]]

有效地交换密钥。这可以通过带有键的 for 循环轻松完成,但我需要一种更有效的方法来完成任务。这样我就可以在下面的界面中绘制图形:

Graph Table View

非常感谢任何帮助!

【问题讨论】:

    标签: swift dictionary filter nested mapping


    【解决方案1】:

    一种可能的方式是使用reduce(into:_:):

    带样品:

    let rates: [String: [String: Double]] = ["2021-11-14": ["CAD": 1.1,
                                                            "USD": 1.0,
                                                            "EUR": 0.9],
                                             "2021-11-15": ["CAD": 1.11,
                                                            "USD": 1.01,
                                                            "EUR": 0.91]]
    

    这应该可以解决问题:

    let target = rates.reduce(into: [String: [String: Double]]()) { partialResult, current in
        let date = current.key
        let dayRates = current.value
        dayRates.forEach { aDayRate in
            var currencyRates = partialResult[aDayRate.key, default: [:]]
            currencyRates[date] = aDayRate.value
            partialResult[aDayRate.key] = currencyRates
        }
    }
    

    对于逻辑,我们遍历rates 的每个元素。 对于每个 [CurrencyCode: Amount],我们对其进行迭代,并将它们设置为partialResult(在reduce(into:_:) 的内部循环的末尾将是finalResult,即返回值)。

    print(rates)print(target) 的输出(我只是对它们进行了格式化以使其更易于阅读):

    $> ["2021-11-14": ["CAD": 1.1, "EUR": 0.9, "USD": 1.0], 
        "2021-11-15": ["USD": 1.01, "EUR": 0.91, "CAD": 1.11]]
    $> ["EUR": ["2021-11-14": 0.9, "2021-11-15": 0.91], 
        "USD": ["2021-11-15": 1.01, "2021-11-14": 1.0], 
        "CAD": ["2021-11-14": 1.1, "2021-11-15": 1.11]]
    

    【讨论】:

    • 完美运行 - 谢谢!
    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2020-03-23
    • 2021-04-28
    • 1970-01-01
    • 2019-01-06
    • 2011-10-29
    相关资源
    最近更新 更多