我正在构建一个包含两个字段的卡路里计数器:一:输入每份的卡路里。二:输入份数。
还有一个从2000年开始的"剩余cal"标签。每次用户输入数据集时,剩余的卡路里都应该重新计算。
这是我的代码:
class ViewController: UIViewController, UITextFieldDelegate {
//MARK:Properties
@IBOutlet weak var enteredCalories: UITextField!
@IBOutlet weak var enteredServings: UITextField!
@IBOutlet weak var calorieCount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//Communicate user inputs into textFields through Delegate callbacks
enteredServings.delegate = self
//UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
//Hide the keyboard
enteredServings.resignFirstResponder()
return true
}
//MARK:Actions
@IBAction func enterButton(sender: AnyObject) {
let startingCalories = Int(calorieCount.text!)!
if calorieCount != nil {
let calories = Int(enteredCalories.text!)!
let servings = Int(enteredServings.text!)!
let calculation = calories * servings
calorieCount.text = "( startingCalories - calculation)"
enteredServings.text = " "
enteredCalories.text = " "
}
}
}
第一次通过这个过程运行良好。输入cal./serving和#of servings的任意组合,应用程序就会运行,并更新剩余卡路里计数器标签。
每当在文本字段中输入第二个数据集时,我都会收到一个错误,告诉我在一个展开的可选值中没有值。如果cal.counter标签、卡路里/份数字段和份数字段仍然有值,为什么我会出现这个错误?
我是编程的新手,我知道这个问题已经被问过很多次了。我理解这个错误的含义,只是不知道它对我的代码意味着什么,所以我不知道从哪里开始修复它。
如下修改此方法,
@IBAction func enterButton(sender: AnyObject) {
let startingCalories = Int(calorieCount.text!)!
if calorieCount != nil {
if let calories = Int(enteredCalories.text!)!, let servings = Int(enteredServings.text!)!{
let calculation = calories * servings
calorieCount.text = "( startingCalories - calculation)"
enteredServings.text = " "
enteredCalories.text = " "
}
}
这不会让你崩溃,但不确定它是否会像预期的那样工作。尝试使用断点检查值,或者尝试使用print()在控制台上打印它们。