致命错误:在展开可选值计算时意外发现nil(fatal error: unexpectedly found nil while unwrapping an Optional value Computation)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var yourScore: UITextField!
@IBOutlet weak var totalScore: UITextField!
@IBOutlet weak var labelText: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
let score1: Int = yourScore.text.toInt()!
let score2: Int = totalScore.text.toInt()!
let mistakes = score2 - score1
let scoreFinal = ((((score2 / 2) - mistakes)*23)/score2)+75
labelText.text = "\(scoreFinal)"
}
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.
}
}
我的代码有问题。 是因为数据类型还是什么? 当我加载应用程序时,它只是打开正常,但按下按钮时,应用程序崩溃。
http://i.stack.imgur.com/B2i5Z.png
import UIKit class ViewController: UIViewController { @IBOutlet weak var yourScore: UITextField! @IBOutlet weak var totalScore: UITextField! @IBOutlet weak var labelText: UILabel! @IBAction func buttonPressed(sender: AnyObject) { let score1: Int = yourScore.text.toInt()! let score2: Int = totalScore.text.toInt()! let mistakes = score2 - score1 let scoreFinal = ((((score2 / 2) - mistakes)*23)/score2)+75 labelText.text = "\(scoreFinal)" } 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. } }Something is wrong with my code. Is it because of data types or something? When I load the application, it just opens fine but when the button is pressed, the app crashes.
http://i.stack.imgur.com/B2i5Z.png
最满意答案
if let你可以安全地解包值:
if let score1 = yourScore.text.toInt() { if let score2 = totalScore.text.toInt() { let mistakes = score2 - score1 let scoreFinal = ((((score2 / 2) - mistakes)*23)/score2)+75 labelText.text = "\(scoreFinal)" } else { // no valid score2 } } else { // no valid score1 }You could safely unwrap the values with if let:
if let score1 = yourScore.text.toInt() { if let score2 = totalScore.text.toInt() { let mistakes = score2 - score1 let scoreFinal = ((((score2 / 2) - mistakes)*23)/score2)+75 labelText.text = "\(scoreFinal)" } else { // no valid score2 } } else { // no valid score1 }更多推荐
发布评论