致命错误:在展开可选值计算时意外发现nil(fatal error: unexpectedly found nil while unwrapping an Optional value Computa

编程入门 行业动态 更新时间:2024-10-10 12:24:12
致命错误:在展开可选值计算时意外发现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 }

更多推荐

本文发布于:2023-08-06 10:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448332.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   意外   错误   发现   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!