简体   繁体   中英

How can I reuse a variable later on in Swift

I'm trying to capture a user input (textfield + button) and reuse the result later in the program but I don't know how to do that.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var moneyTextField: UITextField!

    @IBAction func convert(_ sender: Any) {
        let convertion:Double = Double(moneyTextField.text!)!
        print(convertion)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        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])!
                                print(newContentArray[0])
                            }
                        }
                    }
                }
            }
            //
            print("Rate is \(rateValue)");

            DispatchQueue.main.sync(execute: {
                self.resultLabel.text = "the value of the dollar is " + String(rateValue)
            }
        )}
        task.resume()
    }
}

What I want to do is take the let convertion and multiply it by rateValue at the end of the code. I tried different thing but without any results.

after the advice from Joakim Danielson I did that :

import UIKit

class ViewController: UIViewController {

var fxRate: Double?

@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var moneyTextField: UITextField!
@IBAction func convert(_ sender: Any) {



    let convertion:Double = Double(moneyTextField.text!)!
    print(convertion)

    var convertedAmount = 0.0
    if let rate = fxRate, let money = Double(moneyTextField.text) {
        convertedAmount = rate * money
    }
    print(convertedAmount)
}

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 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])!
                            print(newContentArray[0])

                            rateValue = Double(newContentArray[0])!
                            self.fxRate = rateValue
                        }

                    }


                }
            }
        }



        //
        print("Rate is \(rateValue)");

        DispatchQueue.main.sync(execute: {
            self.resultLabel.text = "the value of the dollar is " + String(rateValue)

        }
        )}
     task.resume()
    }




override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

but I have the error : Cannot invoke initializer for type 'Double' with an argument list of type '(String?)' on line 26. Can you please help me? thx!

create a variable outside of your function

 var anyVariableYouWantToAccessLater: Double?

And use this variable anywhere you want.

Since you're downloading the rate during viewDidLoad I am assuming this is what you want to keep.

Add a new property to the class

class ViewController: UIViewController {
    var fxRate: Double?
    ...

In viewDidLoad update this property with the downloaded value

rateValue = Double(newContentArray[0])!
fxRate = rateValue

In the convert func (or wherever you want to use the rate)

@IBAction func convert(_ sender: Any) {
    var convertedAmount = 0.0
    if let rate = fxRate, let money = Double(moneyTextField.text ?? "0") {
        convertedAmount = rate * money
    }
    print(convertedAmount)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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