This is my code. I tried to fix app crashing while textfield is empty. This method worked in my previous app.
While pressing touchCheck button with empty UITextField app is crashing with following error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
I didn't found any answer on stackoverflow that would work for me.
Also, I'm newbie at swift.
@IBOutlet weak var inField: UITextField!
@IBOutlet weak var outLabel: UILabel!
@IBAction func touchCheck(_ sender: Any) {
let alert = UIAlertController(title: "Hey!", message: "Text field is empty. This may cause app crash. Please, enter a positive whole number to text field in order to get number checked!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Got it", style: .default, handler: nil))
var i = 2
var isPrime = true
let number = Int(inField.text!)
if number == 1 {
isPrime = true
}
if (inField.text?.isEmpty)! {
self.present(alert, animated: true)
outLabel.text = String("Text Field is empty!")
} else if isPrime == true {
outLabel.text = String("Number \(number ?? 1) is prime!")
self.view.endEditing(true)
} else if isPrime == false {
outLabel.text = String("Number \(number ?? 1) isn't prime!")
self.view.endEditing(true)
}
while i < number! { //error at this line
if number! % i == 0 {
isPrime = false
}
i += 1
}
}