I am learning Swift/SwiftUI and I faced a problem. The Xcode's writing this:
"Expected to decode Dictionary<String, CurrencyData> but found an array instead."
Here's a code:
import Foundation
import SwiftUI
struct CurrencyData: Codable {
let r030: Int
let txt: String
let rate: Double
let cc: String
let exchangedate: String
}
typealias Currency = [String: CurrencyData]
import SwiftUI
class API: ObservableObject {
@Published var currencyCode: [String] = []
@Published var priceRate: [Double] = []
@Published var exchangeDate: [String] = []
init() {
fetchdata { (currency) in
switch currency {
case .success(let currency):
currency.forEach { (c) in
DispatchQueue.main.async {
self.currencyCode.append(c.value.cc)
self.priceRate.append(c.value.rate)
self.exchangeDate.append(c.value.exchangedate)
}
}
case(.failure(let error)):
print("Unable to featch the currencies data", error)
}
}
}
func fetchdata(completion: @escaping (Result<Currency,Error>) -> ()) {
guard let url = URL(string: "https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json") else { return }
URLSession.shared.dataTask(with: url) { data, responce, error in
if let error = error {
completion(.failure(error))
return
}
guard let safeData = data else { return }
do {
let currency = try JSONDecoder().decode(Currency.self, from: safeData)
completion(.success(currency))
}
catch {
completion(.failure(error))
}
}
.resume()
}
}
CodePudding user response:
Change the type to correctly decode what you receive ( an array obviously )
This should work, but we can't answer for sure since we have no idea of the data. An attached json sample could help.
typealias Currency = [CurrencyData]
CodePudding user response:
Change the exchangeDate
in your CurrencyData model to exchangedate
which need to match exactly the same as api response. It was case sensitive.