在Swift 3中将可选字符串转换为double [英] Convert optional string to double in Swift 3
问题描述
我有一个选项字符串,想将其转换为双精度.
这适用于Swift 2,但是自从转换为Swift 3以来,我的值为0.
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
我已检查,并且纬度具有可选的字符串值,例如-80.234543218675654,但dLati值为0
***************好的,为清楚起见进行了新更新*****************
我有一个其中有一个按钮的viewcontroller,当触摸该按钮时,它将调用另一个viewcontroller并将一些值传递给它
这是第一个viewcontroller
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
}
}
这是第二个名为MapViewController的视图控制器的代码
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
}
.
.
}
谢谢 博尔纳
推荐答案
一种无需使用Foundation类型即可实现此目的的安全方法是使用Double的初始化程序:
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
}
这篇关于在Swift 3中将可选字符串转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!