问题描述
我收到一条错误消息,提示我必须在 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
}