If语句的第一部分正在传递;可选错误

时间:2016-01-28 01:27:54

标签: ios xcode swift if-statement

首先,这是我简单的小型GPA项目的链接:https://www.dropbox.com/sh/prkf2e3u6ok7jmo/AACY8b8_kDfigxluJyEzdZbGa?dl=0

import UIKit

class calccontroller: UIViewController {
@IBOutlet weak var GPA1: UITextField!
@IBOutlet weak var Credits1: UITextField!
@IBOutlet weak var GPA2: UITextField!
@IBOutlet weak var Credits2: UITextField!
@IBOutlet weak var answerLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.






}








override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func calculatorButton(sender: AnyObject) {

    if GPA1 == nil || GPA2 == nil || Credits1 == nil || Credits2 == nil           {
        let title = "Oops"
        let message = "Please add a value to each text field"
        let okText = "OK"

        let alert = UIAlertController(title: title, message: message,     preferredStyle: UIAlertControllerStyle.Alert)

        let okayButton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
        alert.addAction(okayButton)

       presentViewController(alert, animated: true, completion: nil)
    }
    else
    {



        let gpa1text = Float(GPA1.text!)!
        let gpa2text = Float(GPA2.text!)!
        let credits1text = Float(Credits1.text!)!
        let credits2text = Float(Credits2.text!)!

        let firstGrade = gpa1text * credits1text
        let secondGrade = gpa2text * credits2text
        let allGPA = firstGrade + secondGrade
        let allCredits = credits1text + credits2text
        let finalGrade = allGPA / allCredits

        answerLabel.text = "\(finalGrade)"

        GPA1.resignFirstResponder()
        GPA2.resignFirstResponder()
        Credits1.resignFirstResponder()
        Credits2.resignFirstResponder()
    }

}


}

无论如何,我有一个简单的4文本字段,1个按钮和1个标签设置。我以为我已经成功设置了代码,如果每个文本字段都没有保存值,则会弹出一个ui警报值,要求在每个文本框中输入一个值。如果有4个值,则应用程序将完成"数学。"但是,当我将所有4个都清空时,或者如果我在所有4个填充后单击按钮然后删除1个文本字段,我的应用程序崩溃..."在展开可选值"时意外地发现nil。我发现它令人沮丧(这可能是我最后的一个简单的错误,但在我看来,我不应该有这个值,因此当文本字段为零时,我的弹出警报就会被使用。

谢谢你的时间,Jon。

1 个答案:

答案 0 :(得分:1)

你的逻辑错误。

由于您创建了IBOutlet并检查了nil,因此如果您从storyboard或nib实例化View Controller,它将始终返回false。

您要做的是检查其值是否为空。所以像这样的事情应该可以做到这一点

if GPA1.text.isEmpty || GPA2.text.isEmpty || Credits1.text.isEmpty || Credits2.text.isEmpty {
    // show alert
} else {
    // do your calculation
}