简体   繁体   中英

Struct in Swift accesing multi-nested struct

I am learning Swift and would like help on the following:

I am reading in the following JSON file format:

{
   "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
}

I would like to be able to pass in a parameter variable XXXXX that would let me print out for example (Currencies.XXXXX.rate), where I could let XXXXX to be eur, usd, etc. What would be the best way to approach this dataset and/or problem of calling the right variable? Thanks in advance

I elaborate a little for you. So when you decode to your first struct, you are decoding to type USD for the string usd in your Json. USD also has properties they are used to decode the dictionary for use in 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 

If you're asking about decode strategy, you may want to rephrase the question. For example:

  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 )

You can try

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

With

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM