快速将字符串数组转换为Double [英] convert array of string into Double in swift
问题描述
我正在尝试将字符串快速转换为双精度型.我设法从网站(www.x-rates.com)提取字符串到一个数组中,但是之后我无法将其转换为double,以便对此数字进行一些处理.谁能告诉我应该做什么或做错了什么?我知道我的标签现在不会更新,但我会稍后进行更新,我要做的第一件事就是转换.非常感谢!
I'm trying to convert a string into a double in swift. I managed to extract the string from a website (www.x-rates.com) into an array but I cannot convert it after in a double in order to make some work around this number. Can anyone tell me what I'm supposed to do or what I did wrong? I know that my label don't update now but I will do it later, the first thing that I'm trying to do is the conversion. thx a lot!
这是代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var moneyTextField: UITextField!
@IBAction func convert(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: "https://www.x-rates.com/calculator/?from=EUR&to=USD&amount=1")!
let request = NSMutableURLRequest(url : url)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
var message = ""
if let error = error {
print(error)
} else {
if let unwrappedData = data {
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
var stringSeperator = "<span class=\"ccOutputRslt\">"
if let contentArray = dataString?.components(separatedBy: stringSeperator){
if contentArray.count > 0 {
stringSeperator = "<span"
let newContentArray = contentArray[1].components(separatedBy: stringSeperator)
if newContentArray.count > 0 {
message = newContentArray[0]
var message = Float(newContentArray[0])! + 10
}
}
}
}
}
DispatchQueue.main.sync(execute: {
self.resultLabel.text = "the value of the dollar is " + message
}
)}
task.resume()
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
推荐答案
我将讨论将 String
的 Array
转换为的 Array
Double
.
I will talk about convert an Array
of String
to Array
of Double
.
在迅速的 Array
中有一个名为 map
的方法,它负责映射数组中的值,例如,在map函数中,您将收到一个引用到数组的对象,这会将这个物件转换为您的新阵列ex.
In swift Array
has a method called map
, this is responsable to map the value from array, example, in map function you will receive an object referent to your array, this will convert this object to your new array ex.
let arrOfStrings = ["0.3", "0.4", "0.6"];
let arrOfDoubles = arrOfStrings.map { (value) -> Double in
return Double(value)!
}
结果将为
更新:
@LeoDabus评论了一个重要提示,该示例正在考虑一个完美的数据源,但是如果您有动态源,则可以将?
放回去,它将起作用,但是它将返回一个包含以下内容的数组 nil
@LeoDabus comments an important tip, this example is considering an perfect datasource, but if you have a dynamic source you can put ?
on return and it will work, but this will return an array with nil
喜欢
let arrOfStrings = ["0.3", "0.4", "0.6", "a"];
let arrOfDoubles = arrOfStrings.map { (value) -> Double? in
return Double(value)
}
看一下,返回数组有一个 nil
元素
Look this, the return array has a nil
element
如果您使用@LeoDabus的技巧,则可以保护这种情况,但是您需要了解在问题中需要什么,以便在 map
或 compactMap
If you use the tips from @LeoDabus you will protect this case, but you need understand what do you need in your problem to choose the better option between map
or compactMap
带有 compactMap
let arrOfStrings = ["0.3", "0.4", "0.6", "a"];
let arrOfDoubles = arrOfStrings.compactMap { (value) -> Double? in
return Double(value)
}
查看结果
更新:
与问题的作者(@davidandersson)讨论后,这种使用地图或contactMap的解决方案不是他的问题,我对他的代码进行了修改,效果很好.
After talk with the author (@davidandersson) of issue, this solution with map ou contactMap isn't his problem, I did a modification in his code and work nice.
首先我按照var rateValue:Double = 0.0替换了 var message =",然后将
Float 替换为
Double`
first I replaced var message = "" per var rateValue:Double = 0.0 and replaced
Floatto
Double`
查看最终代码
let url = URL(字符串:"https://www.x-rates.com/calculator/?from=EUR&to=USD&amount=1 )!
let url = URL(string: "https://www.x-rates.com/calculator/?from=EUR&to=USD&amount=1")!
let request = NSMutableURLRequest(url : url)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
var rateValue:Double = 0.0;
if let error = error {
print(error)
} else {
if let unwrappedData = data {
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
var stringSeperator = "<span class=\"ccOutputRslt\">"
if let contentArray = dataString?.components(separatedBy: stringSeperator){
if contentArray.count > 0 {
stringSeperator = "<span"
let newContentArray = contentArray[1].components(separatedBy: stringSeperator)
if newContentArray.count > 0 {
rateValue = Double(newContentArray[0])! + 10
}
}
}
}
}
//
print("Rate is \(rateValue)"); //Rate is 11.167
}
task.resume()
希望能为您提供帮助
这篇关于快速将字符串数组转换为Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!