我试图在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)
}
1条答案
按热度按时间qgelzfjb1#
看起来你在
validateAnswer()
函数中解包userAnswer
时遇到了问题。你正在使用可选绑定从Int(answerField?.text ?? "")
表达式中安全地解包userAnswer
。但是,你仍然试图在if let
块的作用域之外使用userAnswer
,这是不可能的。要解决此问题,您可以将依赖于
userAnswer
的代码移动到if let
块中。下面是修改后的validateAnswer()
函数:这样,使用
userAnswer
的代码只有在它具有有效值时才被执行,并且您不会遇到“Unexpectedly found nil while unwrapping an Optional value”错误。