Reputation: 13
Trying to do something so simple but it's simply not working for me.
CODE:
let long = index["Longitude"] as! String
let lat = index["Latitude"] as! String
print(long as Any)
print(lat as Any)
let doubleLong = Double(long)
print(doubleLong as Any)
DEBUG OUTPUT:
-85.1113644443208
32.880541654362
nil
^^^ Why so nil? I will add this is being pulled from a JSON Response. Perhaps this has something to do with it.
Upvotes: 1
Views: 1733
Reputation: 130102
Most likely there is an additional space in your data, note:
print(Double("-85.1113644443208")) // => Optional(-85.111364444320799)
print(Double("-85.1113644443208 ")) // => nil
print(Double(" -85.1113644443208")) // => nil
Try to trim the spaces first:
let doubleLong = Double(long.trimmingCharacters(in: CharacterSet.whitespaces))
or use a NumberFormatter
for parsing:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale(identifier: "en_US_POSIX")
print(numberFormatter.number(from: "-85.1113644443208") as Double?) // => Optional(-85.111364444320799)
print(numberFormatter.number(from: " -85.1113644443208") as Double?) // => Optional(-85.111364444320799)
print(numberFormatter.number(from: "-85.1113644443208 ") as Double?) // => Optional(-85.111364444320799)
Upvotes: 7
Reputation: 105
There are new failable initializers that allow you to do this in more idiomatic and safe way (as many answers have noted, String's double value is not very safe because it returns 0 for non number values. This means that the doubleValue of "foo" and "0" are the same.)
let myDouble = Double(myString)
This returns an optional, so in cases like passing in "foo" where doubleValue would have returned 0, the failable intializer will return nil. You can use a guard, if-let, or map to handle the Optional
Upvotes: 0