ios 为什么在我的UITextField中输入的文本被记录为nil?

ao218c7q  于 2023-04-22  发布在  iOS
关注(0)|答案(1)|浏览(150)

我试图在UITextField中输入一个简单的整数,并根据“正确答案”验证它-但我一直得到错误,即值为nil“致命错误:展开Optional值时意外发现nil”
我做错了什么?
在顶部我定义变量

var answerMessage = String("No Answer")
var answerLabel: SKLabelNode!
var answerField: UITextField?
var answerModal: SKNode?

然后这些是函数

func validateAnswer() {
            // Convert the entered text to an integer
            if let userAnswer = Int(answerField?.text ?? "") {
                // Use the integer value
                print("The entered number is: \(userAnswer)")
            } else {
                // Invalid input, show an error message
                print("Invalid input, please enter a valid number")
            }
           
            // Display a message with the error percentage and the correct answer
            if userAnswer == correctAnswer {
                let answerMessage = "Wow you got a PERFECT answer!! The answer was \(correctAnswer)!"
                print (answerMessage)
                //let createlabel = SKAction.sequence ([createAnswerLabel])
            }
            else {
                // Calculate the error percentage
                let diff = abs(userAnswer - correctAnswer)
                errorPercentage = Int((Double(diff) / Double(correctAnswer)) * 100)
                
                // Determine if the error is positive or negative
                let direction = userAnswer > correctAnswer ? "high" : "low"
                
                // display correct answer
                let answerMessage = "Almost! Your answer is \(errorPercentage)% \(direction), the answer is \(correctAnswer)."
                print (answerMessage)
            }
        return
        }

 func createAnswerLabel () {
        let answerLabel = SKLabelNode(text: "\(answerMessage)")
        answerLabel.fontColor = .black
        answerLabel.position = CGPoint(x: answerLabel.position.x, y: answerLabel.position.y - 50)
        answerModal!.addChild(answerLabel)
        }
qgelzfjb

qgelzfjb1#

看起来你在validateAnswer()函数中解包userAnswer时遇到了问题。你正在使用可选绑定从Int(answerField?.text ?? "")表达式中安全地解包userAnswer。但是,你仍然试图在if let块的作用域之外使用userAnswer,这是不可能的。
要解决此问题,您可以将依赖于userAnswer的代码移动到if let块中。下面是修改后的validateAnswer()函数:

func validateAnswer() {
    // Convert the entered text to an integer
    if let userAnswer = Int(answerField?.text ?? "") {
        // Use the integer value
        print("The entered number is: \(userAnswer)")

        // Display a message with the error percentage and the correct answer
        if userAnswer == correctAnswer {
            let answerMessage = "Wow you got a PERFECT answer!! The answer was \(correctAnswer)!"
            print(answerMessage)
            //let createlabel = SKAction.sequence ([createAnswerLabel])
        } else {
            // Calculate the error percentage
            let diff = abs(userAnswer - correctAnswer)
            errorPercentage = Int((Double(diff) / Double(correctAnswer)) * 100)

            // Determine if the error is positive or negative
            let direction = userAnswer > correctAnswer ? "high" : "low"

            // display correct answer
            let answerMessage = "Almost! Your answer is \(errorPercentage)% \(direction), the answer is \(correctAnswer)."
            print(answerMessage)
        }
    } else {
        // Invalid input, show an error message
        print("Invalid input, please enter a valid number")
    }
    return
}

这样,使用userAnswer的代码只有在它具有有效值时才被执行,并且您不会遇到“Unexpectedly found nil while unwrapping an Optional value”错误。

相关问题