{
"base": "EUR",
"date": "2016-09-23",
"rates": {
"AUD": 1.4685,
"BGN": 1.9558,
"BRL": 3.5931,
"CAD": 1.4625
}
}
I got a json like this, and i tried to get the rates, but got the error, my code like:
let id = json["rates"] as? String
print("rates :" + id!)
I am new to swifty, i want to get each rates separately, can anyone help me? thanks
Try this:
If let id = json["rates"] as? [String:AnyObject] {
print("rates :" + id)
}
You can follow the below mentioned code to get the individual values.
Here the rate is a dictionary type, hence all values can be fetched by its corresponding key values (ie AUD, BGN, etc like this json["rates"]??["AUD"]
) as shown in my code.
My Code :
let id = json["rates"]
print("rates : \(id)");
print("AUD = \(json["rates"]??["AUD"])");
print("BGN = \(json["rates"]??["BGN"])");
print("BRL = \(json["rates"]??["BRL"])");
print("CAD = \(json["rates"]??["CAD"])");
Hope it helps.
Happy coding...
You may do it like this too, it can give as many rates you have in your dictionary.
if let rates = json["rates"] as? [String: AnyObject] {
for rate in rates {
let corresponsdingRate = rate.1 as? Float ?? 0.0
print("\(rate.0) = \(corresponsdingRate)")
}
}
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.