小编典典

致命错误:解开Optional值时意外发现nil

swift

我正在尝试运行此代码,但我不断收到此错误:

致命错误:解开Optional值时意外发现nil

我不明白这意味着什么或为什么得到它。有什么提示吗?

import UIKit

class ViewController: UIViewController {

var lastNumber: String = ""
@IBOutlet var answerField: UILabel
@IBOutlet var operaterLabel: UILabel

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

@IBAction func buttonTapped(theButton: UIButton) {
    if answerField.text == "0"
    {
        answerField.text = theButton.titleLabel.text
    }
    else
    {
        answerField.text = answerField.text + theButton.titleLabel.text
    }
}

@IBAction func plusTapped(theButton: UIButton) {
    // error is talking about the next line
    if operaterLabel.text == ""
    {
        operaterLabel.text = "+"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "+"
    }

}

@IBAction func minusTapped(theButton: UIButton) {
    if operaterLabel.text == ""
    {
        operaterLabel.text = "-"
        lastNumber = answerField.text
        answerField.text = "0"
    }
    else
    {
        enterTapped(nil)
        operaterLabel.text = "-"
    }

}

@IBAction func clearTapped(AnyObject) {
    answerField.text = "0"
    operaterLabel.text = ""
    lastNumber = ""

}

@IBAction func enterTapped(AnyObject?) {

    var num1 = lastNumber.toInt()
    var num2 = answerField.text.toInt()
    if !num1 || !num2
    {
        showError()
        return
    }
    var answer = 0
    if operaterLabel.text == "-"
    {
        var answer = num1! - num2!
    }
    else if operaterLabel.text == "+"
    {
        var answer = num1! + num2!
    }
    else
    {
        showError()
        return
    }
    answerField.text = "\(answer)"

}

func showError()
{
    println("Ther was an error")
}
}

阅读 205

收藏
2020-07-07

共1个答案

小编典典

错误是指以下事实:当可选值设置为nil时,您正在访问可选值的参数(例如,answerField.text当when
answerField为nil时),这很可能是您的两个之一UILabels

如果该行operaterLabel.text == ""引发异常,则您operaterLabel为nil。验证是否已成功将其连接到Interface
Builder文件中的标签。

2020-07-07