Swift 中的结构访问多嵌套结构

时间:2021-07-04 14:11:03

标签: ios json swift

我正在学习 Swift 并希望获得以下方面的帮助:

我正在阅读以下 JSON 文件格式:

{
   "usd":{
      "code":"USD",
      "rate":0.087722492431105,
      "inverseRate":11.399584898769
   },
   "eur":{
      "code":"EUR",
      "rate":0.074110125979945,
      "inverseRate":13.493432736447
   }
}

Struct Currencies: Codable {
        let usd: USD
        let eur: EUR
struct USD: Codable {
        let name: String
        let rate: Double
        let inverseRate: Double
    }
struct EUR: Codable {
    let name: String
        let rate: Double
        let inverseRate: Double
}

我希望能够传入一个参数变量 XXXXX,它可以让我打印出来,例如 (Currencies.XXXXX.rate),我可以让 XXXXX 为欧元、美元等。什么是最好的处理这个数据集的方法和/或调用正确变量的问题? 提前致谢

2 个答案:

答案 0 :(得分:1)

我为你详细说明了一点。 因此,当您解码为第一个结构时,您正在解码为 Json 中的字符串 usd 键入 USD。 USD 还具有用于解码字典以用于 JSON 的属性。

 let currencies = // Your decode strategy
 currencies.usd //is a struct of USD
 currencies.usd.rate //calls the property rate on type USD on type Currencies 

如果您问的是解码策略,您可能需要重新表述这个问题。例如:

  let json = """
        {
        "usd":{
        "code":"USD",
        "rate":0.087722492431105,
        "inverseRate":11.399584898769
        },
        "eur":{
        "code":"EUR",
        "rate":0.074110125979945,
        "inverseRate":13.493432736447
        }
        }
        """.data(using: .utf8)
    let cur = try? JSONDecoder().decode(Currencies.self, from: json!)
    print( cur!.usd.rate )

答案 1 :(得分:0)

你可以试试

 let res = try JSONDecoder().decode([String:Currency].self,from:data)
 print(Array(res.keys)) 
 print(res["usd"]) 

struct Currency: Codable {
  let name: String
  let rate,inverseRate: Double 
}