我开始自学Swift,我是一名真正的初学者,我正在开发一个计算器应用程序,就像一个介绍项目。我一直收到一个线程错误,并且它以NSException类型的未捕获异常终止。我在几个地方读到这通常是由于从故事板到视图控制器的连接丢失或错误引起的,但我三重检查了我的所有连接,我不认为这是问题所在。这是我的视图控制器代码,它有问题吗?我大部分都遵循了教程。
import UIKit
extension String{
var doubleValue: Double{
if let number = NSNumberFormatter().numberFromString(self) {
return number.doubleValue
}
return 0
}
}
class ViewController: UIViewController {
var isTypingNumber = false
var firstNumber:Double? = 0
var secondNumber:Double? = 0
var operation = ""
@IBOutlet var calculatorDisplay: UILabel!
@IBAction func numberTapped(sender: AnyObject) {
var number = sender.currentTitle
if isTypingNumber {
calculatorDisplay.text = calculatorDisplay.text! + number!!
} else{
calculatorDisplay.text = number
isTypingNumber = true
}
}
@IBAction func calculationTapped(sender: AnyObject) {
isTypingNumber = false
firstNumber = calculatorDisplay.text!.doubleValue
operation = sender.currentTitle!!
}
@IBAction func equalsTapped(sender: AnyObject) {
isTypingNumber = false
var result = 0.0
secondNumber = calculatorDisplay.text!.doubleValue
if operation == "+"{
result = firstNumber! + secondNumber!
} else if operation == "-"{
result = firstNumber! - secondNumber!
} else if operation == "*"{
result = firstNumber! * secondNumber!
}
else if operation == "/"{
result = firstNumber! / secondNumber!
}
calculatorDisplay.text = "\(result)"
}
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.
}
}
我真的很感激我能得到任何帮助!
答案 0 :(得分:1)
自首次将其安装到Storyboard / xib以来,您是否碰巧更改了任何IBOutlet或IBAction的名称?
尝试在Interface Builder中转到viewcontroller,右键单击VC对象以查看所有连接的插座,并检查所有内容是否已连接并且没有任何死链接。 (即,如果您将func equalsTapped()
重命名为func equalsTapped(sender: AnyObject)
,则会引发异常,因为equalsTapped
不再存在,而equalsTapped:
现在已经存在,并且连接是第一个。)