Convert optional string to double in Swift 3

2019-06-15 00:19发布


I have a option string and want to convert that to double.
this worked in Swift 2 , but since converted to Swift 3, I am getting value of 0.

var dLati = 0.0
dLati = (latitude as NSString).doubleValue

I have check and latitude has a optional string value of something like -80.234543218675654 , but dLati value is 0

*************** ok, new update for clarity *****************
I have a viewcontroller which i have a button in it, and when the button is touched, it will call another viewcontroller and pass a few values to it here is the code for the first viewcontroller

var currentLatitude: String? = ""
var currentLongitude: String? = ""
var deviceName = ""
var address = ""
// somewhere in the code, currentLatitude and currentLongitude are get set  
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "map" {
       let destViewController : MapViewController = segue.destination as! MapViewController
       print(currentLongitude!)  // Print display: Optional(-80.192279355363768)
       print(currentLatitude!) // Print display: Optional(25.55692663937162) 
       destViewController.longitude = currentLongitude!
       destViewController.latitude = currentLatitude!
       destViewController.deviceName = deviceName
       destViewController.address = address
    }
}

Here is the code for the second view controller called MapViewController

   var longitude: String? = " "
   var latitude: String? = ""
   .
   .
   override func viewDidLoad() {
       if let lat = latitude {
          print(lat) // Print display: optiona(25.55692663937162)
          dLati = (lat as NSString).doubleValue
          print(dLati)  // Print display: 0.0
       }
       .
       .
   }

Thanks Borna

标签: ios swift swift3
10条回答
爷的心禁止访问
2楼-- · 2019-06-15 01:00

A safe way to achieve this without needing to use Foundation types is using Double's initializer:

if let lat = latitude, let doubleLat = Double(lat) {
  print(doubleLat)  // doubleLat is of type Double now
}
查看更多
beautiful°
3楼-- · 2019-06-15 01:02

When you get a string with double value something like this

"Optional(12.34567)"

You can use a Regex which takes out the double value from the string. This is the example code for a Regex if the string is "Optional(12.34567)":

let doubleLatitude = location.latitude?.replacingOccurrences(of: "[^\\.\\d+]", with: "", options: [.regularExpression])
查看更多
霸刀☆藐视天下
4楼-- · 2019-06-15 01:05

You can do this simply in one line.

var latitude: Double = Double("-80.234543218675654") ?? 0.0

This creates a variable named latitude that is of type Double that is either instantiated with a successful Double from String or is given a fallback value of 0.0

查看更多
仙女界的扛把子
5楼-- · 2019-06-15 01:09

In swift 3.1, we can combine extensions and Concrete Constrained Extensions

extension Optional where Wrapped == String
{
    var asDouble: Double
    {
        return NSString(string: self ?? "").doubleValue
    }
}

Or

extension Optional where Wrapped == String
{
        var asDouble: Double
        {
            return Double(str ?? "0.00") ?? 0.0
        }
}
查看更多
登录 后发表回答