I am creating a simple guessing game on Xcode where the user has to correctly guess the number (between 0 and 5). I thought that I had checked for a nil value for my textFieldInt
to ensure the app does not crash if no value is submitted. Unfortunately this does not seem to be the case and I am not sure where my fault lies.
If I do not enter a value and press the button, I receive the following error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
I have had this issue before and managed to solve it by correctly checking the right optional for nil. Though now it seems to still have 'unexpectedly found nil' even though a nil value has been accounted for.
@IBOutlet var textField: UITextField!
@IBOutlet var label: UILabel!
@IBAction func buttonTapped(_ sender: Any) {
let textFieldInt: UInt32 = UInt32(textField.text!)!
let number = arc4random_uniform(6)
if textFieldInt != nil {
if textFieldInt != number {
label.text = "Wrong! It was \(number)"
}
else if textFieldInt == number {
label.text = "You're right!"
}
else {
label.text = "Please enter a number!"
}
}
}