以后如何在Swift

时间:2018-07-31 15:44:31

标签: swift

我正在尝试捕获用户输入(文本字段+按钮),并在以后的程序中重用结果,但是我不知道该怎么做。

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

我想做的是在代码末尾将let convertion乘以rateValue。我尝试了其他事情,但没有任何结果。

根据约翰·丹尼尔森(Joakim Danielson)的建议 我做到了:

导入UIKit

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.
    }

}

但我遇到错误:在第26行中,无法使用类型为((String?)'的参数列表来调用类型为'Double'的初始化程序。请您帮我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

在函数外创建变量

 var anyVariableYouWantToAccessLater: Double?

并在任何需要的地方使用此变量。

答案 1 :(得分:0)

由于您正在viewDidLoad期间下载价格,所以我假设这是您要保留的价格。

向类添加新属性

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

viewDidLoad中,使用下载的值更新此属性

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

convert函数中(或您要使用费率的任何地方)

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