Dominik
Dominik

Reputation: 419

Unable to convert String to double Swift

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

Upvotes: 0

Views: 6706

Answers (3)

Midhun
Midhun

Reputation: 2187

please try below one, it will work perfectly

extension String {

var toDoubleVal: Double {

    return Double(self) ?? 0.0
}

}

Upvotes: -1

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

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()
    }

Upvotes: 3

Josh Homann
Josh Homann

Reputation: 16327

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)

Upvotes: 1

Related Questions