我已经制作了一个解决二次方程式的应用程序(只是为了看看能否),但是,如果用户意外地没有为其中一个插槽输入值,我不希望应用程序崩溃。请帮忙。
@IBAction func solveButton(sender: AnyObject) {
let a:Double! = Double(textFieldA.text!) // textfieldA is UITextField
let b:Double! = Double(textFieldB.text!) // textfieldB is UITextField
let c:Double! = Double(textFieldC.text!) // textFieldC is UITextField
// This is for if the a value is nil
if a == nil && b == nil && c == nil{
errorTextField.text = "Please do not leave an empty value, all quadratic equations must have 3 values!"
answerLabel.text = " "
answerLabelNegative.text = " "
whatEquation.text = " "
return
} else {
let a:Double! = Double(textFieldA.text!) // textfieldA is UITextField
let b:Double! = Double(textFieldB.text!) // textfieldB is UITextField
let c:Double! = Double(textFieldC.text!) // textFieldC is UITextField
let x:Double = (b * b)
let y:Double = -4 * a * c //Here I get EXC_BAD_INSTRUCTION error
let xy:Double = x + y
let az:Double = sqrt(xy)
let finalTopPlus:Double = -b + az
let finalTopMinus:Double = -b - az
let aTwo:Double = 2 * a
let finalEquationPositive:Double = finalTopPlus / aTwo
let finalEquationNegative:Double = finalTopMinus / aTwo
answerLabel.text = "Positive x = \(finalEquationPositive)"
answerLabelNegative.text = "Negative x = \(finalEquationNegative)"
let aValue = a < 0 ? "-" : " "
let bValue = b < 0 ? " " : "+"
let cValue = c < 0 ? " " : "+"
whatEquation.text = "Equation: \(aValue) \(a)x² \(bValue) \(b)x \(cValue) \(c)"
}
答案 0 :(得分:1)
您的if
语句会检查所有值是否为nil
。您想查看其中是否有nil
。
将if
更改为:
if a == nil || b == nil || c == nil {
我没有在Swift中编程,但我得到的印象是,您应该进行许多其他改进,以验证值不是nil
。
答案 1 :(得分:0)
在Swift中,您应该仔细考虑是否要强制解包(!)值或有条件地解包值(?) - 强制解包nil
会给您一个运行时异常。
例如,选择您的第一行。这应该是:
let a = Double(textFieldA.text!)
这将导致a
成为Double?
- 即它是可选的,因此它可能是零。强制解包textFieldA.text
值是可以的,因为这将由您的故事板设置(或者您创建文本字段),此处的零值表示您需要调查和解决的严重错误。
一旦你有选项,你可以使用Swift guard
语句来检查nil。
使用guard
语句后,您可以放心使用!强制拆开价值,因为你知道它们不是。
@IBAction func solveButton(sender: AnyObject) {
guard let a = Double(textFieldA.text!),
let b = Double(textFieldB.text!),
let c = Double(textFieldC.text!) else {
errorTextField.text = "Please do not leave an empty value, all quadratic equations must have 3 values!"
answerLabel.text = " "
answerLabelNegative.text = " "
whatEquation.text = " "
return
}
let x = (b * b)
let y = -4 * a * c
let xy = x + y
let az = sqrt(xy)
let finalTopPlus= -b + az
let finalTopMinus = -b - az
let aTwo= 2 * a
let finalEquationPositive = finalTopPlus / aTwo
let finalEquationNegative = finalTopMinus / aTwo
answerLabel.text = "Positive x = \(finalEquationPositive)"
answerLabelNegative.text = "Negative x = \(finalEquationNegative)"
let aValue = a < 0 ? "-" : " "
let bValue = b < 0 ? " " : "+"
let cValue = c < 0 ? " " : "+"
whatEquation.text = "Equation: \(aValue) \(a)x² \(bValue) \(b)x \(cValue) \(c)"
}
请注意,在Swift中,您只需要定义变量或常量的类型(如果无法推断)。 Double()
返回一个可选的Double,添加两个双打的结果是Double,因此您不需要声明该常量将是Double。