ios 在 Swift 3 中将可选字符串转换为双精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40372656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert optional string to double in Swift 3
提问by borna
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.
我有一个选项字符串,想将其转换为双精度。
这在 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
*************** 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
我检查了一下,纬度有一个可选的字符串值,比如 -80.234543218675654 ,但 dLati 值为 0
*************** 好的,为了清晰起见,新的更新 ******** *********
我有一个视图控制器,里面有一个按钮,当按钮被触摸时,它会调用另一个视图控制器并向它传递一些值,这里是第一个视图控制器的代码
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
谢谢博尔纳
回答by BJ Miller
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
}
回答by Rajan Maheshwari
Unwrap the latitude
value safely and then use
latitude
安全地解开值然后使用
var dLati = 0.0
if let lat = latitude {
dLati = (lat as NSString).doubleValue
}
回答by user3441734
let dLati = Double(latitude ?? "") ?? 0.0
回答by MjZac
This code works fine.
这段代码工作正常。
var dLati = 0.0
let latitude: String? = "-80.234543218675654"
if let strLat = latitude {
dLati = Double(strLat)!
}
回答by Sumit Meena
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)"
:
您可以使用从字符串中取出双精度值的正则表达式。这是正则表达式的示例代码,如果字符串是"Optional(12.34567)"
:
let doubleLatitude = location.latitude?.replacingOccurrences(of: "[^\.\d+]", with: "", options: [.regularExpression])
回答by achi
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 类型,该变量要么使用来自 String 的成功 Double 实例化,要么被赋予回退值 0.0
回答by Rashwan L
Don′t convert it to an NSString
, you can force it to a Double
but have a fallback if it fails. Something like this:
不要将其转换为 an NSString
,您可以强制将其转换为 aDouble
但如果失败则有回退。像这样的东西:
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
值,请执行以下操作(注意 let 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")
}
回答by borna
Actually the word optional was part of the string. 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
实际上,可选一词是字符串的一部分。不确定它是如何添加到字符串中的?但是我修复它的方式是这样的。纬度是这个字符串“可选(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
回答by Karthik
In swift 3.1, we can combine extensions and Concrete Constrained Extensions
在swift 3.1 中,我们可以结合扩展和具体约束扩展
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
}
}
回答by Shakeel Ahmed
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)
}