简体   繁体   English

在Swift 3中将可选字符串转换为double

[英]Convert optional string to double in Swift 3


I have a option string and want to convert that to double. 我有一个选项字符串,并希望将其转换为double。
this worked in Swift 2 , but since converted to Swift 3, I am getting value of 0. 这在Swift 2中有效,但自从转换为Swift 3后,我的值为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 我有检查和纬度有一个可选的字符串值,如-80.234543218675654,但dLati值为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 我有一个viewcontroller,我有一个按钮,当触摸按钮时,它将调用另一个viewcontroller并传递一些值到这里是第一个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 这是第二个视图控制器的代码,称为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 谢谢博尔纳

A safe way to achieve this without needing to use Foundation types is using Double's initializer: 在不需要使用Foundation类型的情况下实现此目的的一种安全方法是使用Double的初始化程序:

if let lat = latitude, let doubleLat = Double(lat) {
  print(doubleLat)  // doubleLat is of type Double now
}

Unwrap the latitude value safely and then use 安全打开latitude值然后使用

var dLati = 0.0

if let lat = latitude {
    dLati = (lat as NSString).doubleValue
}
let dLati = Double(latitude ?? "") ?? 0.0

This code works fine. 这段代码工作正常。

var dLati = 0.0
let latitude: String? = "-80.234543218675654"
if let strLat = latitude {
    dLati = Double(strLat)!
}

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. 您可以使用Regex从字符串中取出double值。 This is the example code for a Regex if the string is "Optional(12.34567)" : 如果字符串是"Optional(12.34567)"这是Regex的示例代码:

let doubleLatitude = location.latitude?.replacingOccurrences(of: "[^\\.\\d+]", with: "", options: [.regularExpression])

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 这将创建一个名为latitude的变量,其类型为Double,可以使用成功的Double from String进行实例化,或者返回值为0.0

Don´t convert it to an NSString , you can force it to a Double but have a fallback if it fails. 不要将它转换为NSString ,你可以将它强制为Double但如果失败则会有后备。 Something like this: 像这样的东西:

let aLat: String? = "11.123456"
let bLat: String? = "11"
let cLat: String? = nil

let a = Double(aLat!) ?? 0.0 // 11.123456
let b = Double(bLat!) ?? 0.0 // 11
let c = Double(cLat!) ?? 0.0 // 0

So in your case: 所以在你的情况下:

dLati = Double(latitude!) ?? 0.0

Update: To handle nil values do the following (note that let cLat is nil : 更新:要处理nil值,请执行以下操作(请注意,让cLat为nil

// Will succeed
if let a = aLat, let aD = Double(aLat!) {
    print(aD)
}
else {
    print("failed")
}

// Will succeed
if let b = bLat, let bD = Double(bLat!) {
    print(bD)
}
else {
    print("failed")
}

// Will fail
if let c = cLat, let cD = Double(cLat!) {
    print(cD)
}
else {
    print("failed")
}

Actually the word optional was part of the string. 实际上,Optional这个词是字符串的一部分。 Not sure how it got added in the string? 不确定它是如何添加到字符串中的? But the way I fixed it was like this. 但我修复它的方式就是这样。 latitude was this string "Optional(26.33691567239162)" then I did this code latitude是这个字符串“Optional(26.33691567239162)”然后我做了这个代码

let start = latitude.index(latitude.startIndex, offsetBy: 9) 
let end = latitude.index(latitude.endIndex, offsetBy: -1) 
let range = start..<end 
latitude = latitude.substring(with: range) 

and got this as the final value 并将此作为最终值
26.33691567239162 26.33691567239162

In swift 3.1 , we can combine extensions and Concrete Constrained Extensions swift 3.1中 ,我们可以组合扩展和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
        }
}

Swift 4 斯威夫特4

 let YourStringValue1st = "33.733322342342" //The value is now in string
 let YourStringValue2nd = "73.449384384334" //The value is now in string

 //MARK:- For Testing two Parameters 
 if let templatitude = (YourStringValue1st as? String), let templongitude = (YourStringValue2nd as? String)
 {
     movetosaidlocation(latitude: Double(templat)!, longitude: Double(templong)!, vformap: cell.vformap)
 }


 let YourStringValue = "33.733322342342" //The value is now in string
 //MARK:- For Testing One Value
 if let tempLat = (YourStringValue as? String)
 {
      let doublevlue = Double(tempLat)
      //The Value is now in double (doublevlue)
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM