I am trying to decode JSON object using Codable with Swift 4:
{
USD: {
"15m": 9977.49,
last: 9977.49,
buy: 9979.36,
sell: 9975.62,
symbol: "$"
},
AUD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
},
TBD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
}
}
This is what I've done so far with a model of an object:
struct Currency: Codable {
let fifteenMin: Double?
let last: Double?
let buy: Double
let sell: Double
let symbol: String
enum CodingKeys: String, CodingKey {
case fifteenMin = "15m"
case last
case buy
case sell
case symbol
}
}
And this is how I decode that:
var currencyName = [String]()
var currenciesArray = [Currency]()
func fetchCurrencyData() {
guard let urlString = API.RateURL.absoluteString else { return }
guard let url = URL(string: urlString) else { return }
let jsonData = try! Data(contentsOf: url)
let decoder = JSONDecoder()
do {
let currenciesData = try decoder.decode([String: Currency].self, from: jsonData)
for currency in currenciesData {
self.currencyName.append(currency.key)
self.currenciesArray.append(currency.value)
}
} catch let err {
print(err.localizedDescription)
}
}
So when I want to populate rows in tableView with that Data I use "for loop" and append "USD", "AUD" and so on in one array and Currency object in another array.
What is the better way of fetching data and populating Currency object. Cuz I am pretty sure that fetching and appending the same object of JSON into two separate arrays isn't good practice I assume.
If my question isn't clear I can explain in more details what I would like to achieve.
Thank you.