joost12345
joost12345

Reputation: 1

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

Upvotes: 0

Views: 56

Answers (2)

SeaSpell
SeaSpell

Reputation: 758

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 )

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

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 
}

Upvotes: 0

Related Questions