1

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!

Here is the code:

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.
    }
}
1
  • thx for your answers but I cannot find a way to fix my prob. does anyone have any idea? thx! Commented Jul 25, 2018 at 12:28

2 Answers 2

1

I will talk about convert an Array of String to Array of Double.

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)!
}

The result will be return example

UPDATE:

@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

like that

let arrOfStrings = ["0.3", "0.4", "0.6", "a"];

let arrOfDoubles = arrOfStrings.map { (value) -> Double? in
    return Double(value)
}

Look this, the return array has a nil element

Second example

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

example with compactMap

let arrOfStrings = ["0.3", "0.4", "0.6", "a"];

let arrOfDoubles = arrOfStrings.compactMap { (value) -> Double? in
    return Double(value)
}

look the result

compactMap example result

UPDATE:

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.

first I replaced var message = "" per var rateValue:Double = 0.0 and replacedFloattoDouble`

look the final code

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()

Hope to help you

Sign up to request clarification or add additional context in comments.

6 Comments

This will crash if there is am invalid string. Better to use compactMap(Double.init)
thx. do you know how I can apply that to my prob? I made some tests but without any results. thx a lot
@LeoDabus thanks for this tip, I updated my post to explain better, if you have more information pls share with us :D
@davidandersson I need more information about your error
@ViTUu: there is no error but I cannot convert the data dowloaded from the web into a double. the data that I want to get is a number and I get it as a string, who doesn't allow me to work on it after.
|
0

The reason your code doesn’t work in my opinion is that you have two variables with the same name that are defined in different scopes and you use the wrong one at the end.

At the beginning you define

var message = ""

And then when converting to a number further down

var message = Float(newContentArray[0])! + 10

So change the last line to something like

var number = Float(newContentArray[0])! + 10

And use number in your calculations. Although I think

var number = Double(message)

should work equally fine since you have assigned newContentArray[0] to message already and Double is more commonly used than Float (I don’t understand + 10)

5 Comments

@ Joakim: good try but I got a new error: Definition conflicts with previous value the +10 was only a test to see if the value was updated or not
If you had taken the time to google that error you would have find that it is in no way related to your question, an example. Did you check if number contained the right value?
yes I know that s not related. I just gave you the result of what you told me to do. but I ll keep digging. thx for your help
Well, you didn’t give me the results exactly.
@davidandersson But you declared the same variable twice, look at the row above the error!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.