I have a Json (received as text) that I convert it like this:
if let jsonData = raw.data(using: String.Encoding.utf8) {
if let json = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) {
let products = json["products"] as! [Dictionary<String, AnyObject>]
Products contains an array of products (also json), where I have keys which value can be String, Float, Double... one key has a value that it can be any kind of number.
This field when it is received on text from endpoint looks like this: \"min_size\":\"0.01\"
but also can have values like \"min_size\":\"1\"
, or \"min_size\":\"0.001\"
. After my json conversion looks like this (printing using po
):
▿ 1 : 2 elements
- key : "min_size"
- value : 1
Or
▿ 15 : 2 elements
- key : "min_size"
- value : 0.01
But then, when I'm trying to access it on my code (I want to read it as a float, independently if it is a 1 or a 0.01), I get this:
let k = item["min_size"] // contains > ▿ Optional<Any> - some : 0.01
let i = item["min_size"] as? Float // contains > nil
let j = item["min_size"] as? Int // contains > nil
let y = item["min_size"] as? NSString // contains > "0.01"
let z = y!.floatValue // contains > "0.009999997"
I'm new on Swift, and I don't understand what's going on here.
- Why I cannot cast directly the value (1 or 0.01) to float?
- If not, what can I do to get a float number for this field?
- And the most weird for me... why having a NSString that it is "0.01" converting value with floatValue, result is different? Rounding is not an option, because it could be such a long decimal too. It can be any decimal or integer number there.
Any idea what I'm doing wrong?