如何将 UITextField 输入从 String 转换为 Double?

How to convert UITextField input from String to Double?

我收到一条错误消息,说我必须 在 Double(billTotalTextField.text ?? 0.0),

中添加“from”

但后来我收到另一条错误消息说“表达式类型不明确,没有更多上下文”?

这是什么原因?

如何将String输入转换为Double?

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var billTotalTextField: UITextField!
    
    let tipPercentage = 0
    var billTotal = 0.0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @IBAction func tipButtonPressed(_ sender: UIButton) {
        billTotal = Double(from: billTotalTextField.text ?? 0.0)
        
        
        if sender.currentTitle == "0%"{
            let percentage0 = 0.0
            print(billTotal * percentage0)
        }else if sender.currentTitle == "10%"{
            let percentage10 = 0.1
            print(billTotal * percentage10)
        }else if sender.currentTitle == "20%"{
            let percentage20 = 0.2
            print(billTotal * percentage20)
        }
    

}

}

您在一个参数中混合了字符串和数值,因此您需要将其设为同一类型,如下所示:

billTotal = Double(billTotalTextField.text ?? "0.0") ?? 0.0

或者更清楚一点:

if let text = billTotalTextField.text {
   billTotal = Double(text) ?? 0.0
}