#arrays #json #swift #dictionary
#массивы #json #swift #словарь
Вопрос:
Я извлекаю значения валюты из онлайн-валютного сервиса.
После того, как я получу массив json всех валют, я выбираю 2 валюты для сравнения.
[{
"symbol": "$",
"name": "US Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "USD",
"name_plural": "US dollars"
}, {
"symbol": "CA$",
"name": "Canadian Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "CAD",
"name_plural": "Canadian dollars"
}]
Я создаю запрос и отправляю его обратно в свой сервис.
Запрос:
let URLString: String = finalURLPart1 finalURLPart2 finalURLPart3 ""
//print(#function, "URLString: ", URLString)
var request = URLRequest(url: URL(string: URLString)!, timeoutInterval: Double.infinity)
//print(#function, "request: ", request)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertController.Style.alert)
let okButton = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
} else {
// 2- Getting the response (Data)
if data != nil {
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>
//Async
print(jsonResponse)
DispatchQueue.main.async {
if let rates = jsonResponse["rates"] as? [String : Any] {
for convertedValue in rates.values {
print("convertedValue: ", convertedValue)
print("Type: ", type(of: convertedValue))
}
}
}
} catch {
print("Error")
}
}
}
}
// 3- Process the data (Parsing: or JSON Serialization)
task.resume() // starting the task
//semaphore.wait()
}
Я получаю это обратно:
["base": BAM, "date": 2020-10-13 22:18:00 00, "rates": {
BDT = "51.11942821250704";
}]
for convertedValue in rates.values {
print("convertedValue: ", convertedValue)
print("Type: ", type(of: convertedValue))
}
Вывод:
convertedValue: 51.11942821250704
Type: __NSCFString
Как я могу получить значение с плавающей запятой для convertedValue?
Комментарии:
1. пожалуйста, отредактируйте свой вопрос и опубликуйте полученную строку JSON и правильно отформатируйте свой пост
2. Подойдет. Спасибо за форматирование..
3. возвращаемое значение не является допустимым json
Ответ №1:
Если я правильно понял, вы можете получить значение BDT
key из объекта rates
JSON, привести его к типу (который есть String
), а затем преобразовать его в Float
using init?(_:)
initializer:
if let rates = jsonResponse["rates"] as? [String: Any] {
if let stringValue = rates.values.first as? String, let convertedValue = Float.init(stringValue) {
print("convertedValue:", convertedValue)
print("Type:", type(of: convertedValue))
}
}
Это выведет:
convertedValue: 51.119427 Type: Float
Комментарии:
1. Спасибо за ответ. Это
stringValue = rates["BDT"]
проблема, поскольку каждая валюта имеет свой собственный код (например, «BDT»)2. @ICT1901 вы можете использовать
rates.values.first
, если в объекте всегда есть только один ключrates
. Я обновил свой ответ.