0

For my app I need to convert a String to a double because I have to create a CLLocationObject for my App and therefore I need those doubles. Therefore I tried this:

 let lat = (cityObject.lat as! NSString).doubleValue

if I print the normal String I get the following:

some("Optional(52.523553)") some("Optional(13.403783)")

and if I print my double value, I get the following:

0.0 0.0

Chris Drappier
  • 5,280
  • 10
  • 40
  • 64
Dominik
  • 419
  • 2
  • 6
  • 16

3 Answers3

3

Please try this:

extension String {
    func toDouble() -> Double? {
        return NumberFormatter().number(from: self)?.doubleValue
    }
}

You can access like that:

var myString = "1.2"
var myDouble = myString.toDouble()

enter image description here

You can remove optional as below:

if let data:NSDictionary = snap.value as! NSDictionary,  let lat = data.value(forKey: "lat"),let lng = data.value(forKey: "lng") {
    //then use thes let long to convert in Double

    let latValue = lat.toDouble()
    let lngValue = lng.toDouble()
    }
Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26
  • alue of type 'String' has no member 'toDouble' – Dominik Apr 17 '18 at 20:38
  • Can you explain it more? – Jogendar Choudhary Apr 17 '18 at 20:40
  • your code is working but my issue isnt fixed because i found out that i receive an Optional String from my Firebase Database and thats not working with your extension. Do you know how i can remove the Optional Extension? – Dominik Apr 17 '18 at 20:55
  • it would be great if you could check my code: https://stackoverflow.com/questions/49887481/how-to-remove-optional-from-string-value-swift – Dominik Apr 17 '18 at 21:08
  • @Dominik try `if let dict = snap.value as? [String: Any], let lat = dict["lat"] as? Double, let lng = dict["lng"] as? Double, let radius = dict["radius"] as? Double {` – Leo Dabus Apr 17 '18 at 23:10
1

Double has a failable initializer that takes a String and returns an optional Double?, since obviously not all Strings are valid Doubles. That means you need to unwrap the result:

guard let value = Double("1.0") else {
   print("Not a valid Double")
}
print(value)
Josh Homann
  • 15,933
  • 3
  • 30
  • 33
-1

please try below one, it will work perfectly

extension String {

var toDoubleVal: Double {

    return Double(self) ?? 0.0
}

}

midhun p
  • 1,987
  • 18
  • 24