0

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

    }


}
Waven
  • 13
  • 1

2 Answers2

0

You need to check if the text field is empty before your declaration of number.

This will make number nil as it is right now when the field is empty

let number = Int(inField.text!)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

This

guard let number = Int(inField.text!) else { return }

return an optional int?

that may be nil check it before usage

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87